08
2017
08

miniprofile的使用方法并用log4net记录到日志文件

1、正常使用方法参考

http://www.cnblogs.com/jiekzou/p/6374726.html


2、自定义类实现IStorage接口并使用

(仅重要代码供参考,其他非miniprofile相关的代码如报错可去掉)


//MiniprofilerLog4NetStorage.cs

using Kulv.YCF.Framework.CommomHelper;

using log4net;

using StackExchange.Profiling;

using StackExchange.Profiling.Storage;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace Kulv.YCF.App_Start

{

    public class MiniprofilerLog4NetStorage : IStorage

    {

        private ILog logger = log4net.LogManager.GetLogger("Log4NetProfiler");

        public List<Guid> GetUnviewedIds(string user)

        {

            return new List<Guid>();

        }

        public IEnumerable<Guid> List(int maxResults, DateTime? start = default(DateTime?), DateTime? finish = default(DateTime?), ListResultsOrder orderBy = ListResultsOrder.Descending)

        {

            return new List<Guid>();

        }

        public MiniProfiler Load(Guid id)

        {

            return null;

        }

        public void Save(MiniProfiler profiler)

        {

            if (profiler.DurationMilliseconds >= 1000 && logger.IsInfoEnabled)//记录耗时长的日志

                logger.Info(JsonUtility.ToJson(profiler));

        }

        public void SetUnviewed(string user, Guid id)

        {

            return;

        }

        public void SetViewed(string user, Guid id)

        {

            return;

        }

    }

}


//MiniProfilerLocalCacheStorage.cs

using StackExchange.Profiling;

using StackExchange.Profiling.Storage;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Security;


namespace Kulv.YCF.AdminWeb.App_Start

{

    public class MiniProfilerLocalCacheStorage : IStorage

    {

        private const string CK_SHOWPROFILER = "ShowProfiler";

        /// <summary>

        /// cookie滑动过期时间,单位:分钟

        /// </summary>

        private const int COOKIE_TIMEOUT = 10;

        private HttpRuntimeCacheStorage locaCacheStorage;

        public MiniProfilerLocalCacheStorage(TimeSpan cacheDuration)

        {

            locaCacheStorage = new HttpRuntimeCacheStorage(cacheDuration);

        }

        public List<Guid> GetUnviewedIds(string user)

        {

            return locaCacheStorage.GetUnviewedIds(user);

        }

        public IEnumerable<Guid> List(int maxResults, DateTime? start = default(DateTime?), DateTime? finish = default(DateTime?), ListResultsOrder orderBy = ListResultsOrder.Descending)

        {

            return locaCacheStorage.List(maxResults, start, finish, orderBy);

        }

        public MiniProfiler Load(Guid id)

        {

            return locaCacheStorage.Load(id);

        }

        public void Save(MiniProfiler profiler)

        {

            if (NeedSave())

            {

                locaCacheStorage.Save(profiler);

            }

        }

        public static bool NeedSave()

        {

            var request = HttpContext.Current.Request;

            var response = HttpContext.Current.Response;

            if (request == null || response == null)

            {

                return false;

            }

            if (request.IsLocal)

            {

                return true;

            }

            if (request.QueryString["ShowProfiler"] == "1")

            {

                AddOrUpdateCookie(response, "1");

                return true;

            }

            if (request.QueryString["ShowProfiler"] == "0")

            {

                AddOrUpdateCookie(response, "0");

                return false;

            }

            if (request.Cookies[CK_SHOWPROFILER] != null && request.Cookies[CK_SHOWPROFILER].Value == "1")

            {

                request.Cookies[CK_SHOWPROFILER].Expires = DateTime.Now.AddMinutes(COOKIE_TIMEOUT);

                return true;

            }

            return false;

        }

        private static void AddOrUpdateCookie(HttpResponse response, string value)

        {

            var cookie = new HttpCookie(CK_SHOWPROFILER, value);

            cookie.Expires = DateTime.Now.AddMinutes(COOKIE_TIMEOUT);

            response.SetCookie(cookie);

        }

        public void SetUnviewed(string user, Guid id)

        {

            locaCacheStorage.SetUnviewed(user, id);

        }

        public void SetViewed(string user, Guid id)

        {

            locaCacheStorage.SetViewed(user, id);

        }

    }

}


//Global.asax.cs

        private ILog logger = log4net.LogManager.GetLogger(typeof(MvcApplication));

        private Lazy<MultiStorageProvider> MultiStorageProvider = new Lazy<MultiStorageProvider>(() =>

          {

              return new MultiStorageProvider(new MiniProfilerLocalCacheStorage(new TimeSpan(0, 30, 0)), new YCF.App_Start.MiniprofilerLog4NetStorage());

          }, true);

        protected void Application_Start()

        {

            AppDomain.CurrentDomain.UnhandledException += (sender, arg) =>

            {

                var ex = arg.ExceptionObject as Exception;

                Log4Logger.Error("UnhandledException", ex);

            };

            EnableMiniProfiler();

            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //#if !DEBUG

            //启用压缩

            BundleTable.EnableOptimizations = true;

            //#endif

            //Db初始化

            DatabaseInitializer.Initialize();

            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath("~") + "Config\\log4net.config"));


            DatabaseInitializer.PreCreateView();           

        }

        private void EnableMiniProfiler()

        {

            if (ProfileEnabled)

            {

                //MiniProfilerLog.SetUpLog4Net(); //Set up profiler with logger

                MiniProfiler.Settings.IgnoredPaths = new string[] {

                    "/Assets/",

                    "/Scripts/",

                    "/Content/",

                    "/favicon.ico",

                    "/html/",

                    "/Upload/",

                    "/Template/",

                    "/signalr/",

                 };

                MiniProfiler.Settings.Storage = MultiStorageProvider.Value;

                MiniProfiler.Settings.Results_List_Authorize = IsUserAllowedToSeeMiniProfilerUI;

                MiniProfiler.Settings.Results_Authorize = IsUserAllowedToSeeMiniProfilerUI;

                MiniProfilerEF6.Initialize();

            }

        }

        private bool IsUserAllowedToSeeMiniProfilerUI(HttpRequest httpRequest)

        {

            var principal = httpRequest.RequestContext.HttpContext.User;

            return principal.IsInRole(Constant.Role.Admin.ToString());

        }

        protected void Application_BeginRequest()

        {

            string guid = Guid.NewGuid().ToString();

            LogTrackingIdentifier.SetHeaderForLog(guid);

            Response.AppendToLog("&&traceguid=" + guid);

            try

            {

                if (ProfileEnabled)

                {

                    MiniProfiler.Start(HttpContext.Current.Request.Url.AbsolutePath + "&&traceguid=" + guid);

                    using (MiniProfiler.Current.Step("BeginRequest")) { }

                }

            }

            catch (Exception ex)

            {

                logger.Error("启动MiniProfiler异常", ex);

            }

        }

        protected void Application_EndRequest()

        {

            if (ProfileEnabled)

            {

                using (MiniProfiler.Current.Step("EndRequest")) { }

                MiniProfiler.Stop();

            }

            if (Response != null && MiniProfiler.Current != null)

            {

                Response.AppendToLog("&&tracetime=" + MiniProfiler.Current.DurationMilliseconds);

            }

        }




版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。