MiniProfiler,一个.NET简单但有效的微型分析器
背景
MVC MiniProfiler是Stack Overflow團(tuán)隊(duì)設(shè)計(jì)的一款對ASP.NET MVC的性能分析的小程序。可以對一個(gè)頁面本身,及該頁面通過直接引用、Ajax、Iframe形式訪問的其它頁面進(jìn)行監(jiān)控,監(jiān)控內(nèi)容包括數(shù)據(jù)庫內(nèi)容,并可以顯示數(shù)據(jù)庫訪問的SQL(支持EF、EF CodeFirst等 )。并且以很友好的方式展現(xiàn)在頁面上。
該P(yáng)rofiler的一個(gè)特別有用的功能是它與數(shù)據(jù)庫框架的集成。除了.NET原生的 DbConnection類,profiler還內(nèi)置了對實(shí)體框架(Entity Framework)以及LINQ to SQL的支持。任何執(zhí)行的Step都會包括當(dāng)時(shí)查詢的次數(shù)和所花費(fèi)的時(shí)間。為了檢測常見的錯(cuò)誤,如N+1反模式,profiler將檢測僅有參數(shù)值存在差 異的多個(gè)查詢。
MiniProfiler是以Apache License V2.0協(xié)議發(fā)布的,你可以在NuGet找到。配置及使用可以看這里:http://code.google.com/p/mvc-mini-profiler
概述
在WebApi中,對其性能進(jìn)行分析監(jiān)測是很有必要的。而悲劇的是,MVC項(xiàng)目中可以使用的MiniProfiler或Glimpse等,這些都不支持WebApi項(xiàng)目,而且WebApi項(xiàng)目通常也沒有界面,不能進(jìn)行性能分析的交互。在這篇文章中,我們就來一步步實(shí)現(xiàn)為WebApi項(xiàng)目集成Miniprofiler。集成后,我們可以監(jiān)控EF執(zhí)行效率,執(zhí)行語句,頁面執(zhí)行時(shí)間等,這些結(jié)果將以很友好的方式顯示在界面上。
問題
本質(zhì)上,集成Miniprofiler可以分解為三個(gè)問題:
怎樣監(jiān)測一個(gè)WebApi項(xiàng)目的性能。
將性能分析監(jiān)測信息從后端發(fā)送到UI。
在UI顯示分析監(jiān)測結(jié)果。
實(shí)現(xiàn)方式
首先安裝Miniprofiler,MiniProfiler.EF6
在Global.asax? 加入
using BQoolCommon.Helpers.Model; using Elmah; using ResearchManager.Web.App_Start; using System; using System.Configuration; using System.Web; using System.Web.Mvc; using System.Web.Routing; using StackExchange.Profiling; using StackExchange.Profiling.Mvc; using StackExchange.Profiling.EntityFramework6; using System.Web.Optimization; using NLog; using ResearchManager.Models.ValidateAttribute;namespace ResearchManager.Web {public class MvcApplication : HttpApplication{protected void Application_Start(){AreaRegistration.RegisterAllAreas();FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);RouteConfig.RegisterRoutes(RouteTable.Routes);BundleConfig.RegisterBundles(BundleTable.Bundles);//Remove Header X-AspNetMvc-VersionMvcHandler.DisableMvcResponseHeader = true;AutofacConfig.Bootstrapper();//在 Controller 之前對 Model 做處理(字串 Trim)ModelBinders.Binders.DefaultBinder = new BQoolModelBinder();//註冊自訂的 Validation (複寫預(yù)設(shè)的錯(cuò)誤訊息)CustomerValidation.RegisterCustomerValidation();DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomizedRequired), typeof(RequiredAttributeAdapter));DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomizedStringLength), typeof(StringLengthAttributeAdapter));#region 測試//if (bool.Parse(ConfigurationManager.AppSettings["MiniProfiler"] ?? "false"))//{MiniProfiler.Configure(new MiniProfilerOptions{RouteBasePath = "~/profiler",PopupRenderPosition = RenderPosition.Right, // defaults to leftPopupMaxTracesToShow = 10, // defaults to 15ResultsAuthorize = request => request.IsLocal,ResultsListAuthorize = request =>{return true; // all requests are legit in this example},// Stack trace settingsStackMaxLength = 256, // default is 120 charactersTrackConnectionOpenClose = true}.ExcludeType("SessionFactory") // Ignore any class with the name of SessionFactory).ExcludeAssembly("NHibernate") // Ignore any assembly named NHibernate.ExcludeMethod("Flush") // Ignore any method with the name of Flush.AddViewProfiling() // Add MVC view profiling (you want this));MiniProfilerEF6.Initialize();//}#endregion 測試}protected void Application_BeginRequest(Object source, EventArgs e){BundleTable.EnableOptimizations = false;#region 測試MiniProfiler.StartNew();#endregion 測試}protected void Application_EndRequest(){#region 測試//MiniProfiler.Current?.Stop(); // Be sure to stop the profiler!#endregion 測試}#region Elmahprivate static readonly string _exceptionMsg = "A potentially dangerous Request.Path value was detected from the client";protected void Application_Error(object sender, EventArgs e){Exception ex = Server.GetLastError();Logger nlogger = LogManager.GetCurrentClassLogger();nlogger.Error(ex);if (BQoolCommon.Helpers.Setting.CommonSetting.IsProd()){if (e is ExceptionFilterEventArgs exceptionFilter){if (exceptionFilter.Exception is HttpException httpException && httpException.Message.StartsWith(_exceptionMsg)){Response.Redirect("/");}}Response.Clear();Server.ClearError();Response.StatusCode = 404;}}/// <summary>/// 排除 Elmah 404 寄信通知/// </summary>public void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs e){if (e.Exception is HttpException httpException && (httpException.GetHttpCode() == 404 || httpException.Message.StartsWith(_exceptionMsg))){e.Dismiss();}}/// <summary>/// 自定 Elmah 發(fā)信主旨/// </summary>private void ErrorMail_Mailing(object sender, Elmah.ErrorMailEventArgs e){string machineName = "none server";try{if (Request != null){machineName = Request.ServerVariables["HTTP_HOST"];}}catch{}// 取得 Elamh ErrorMail 的主旨// "$MachineName$ at $ErrorTime$ : {0}"string elmahSubject = e.Mail.Subject;//替換 ErrorMail 的主旨內(nèi)容string emailSubject = string.Format("ResearchManager.Web Error => {0}",elmahSubject.Replace("$MachineName$", machineName));e.Mail.Subject = emailSubject;}#endregion Elmah} }運(yùn)行效果
運(yùn)行項(xiàng)目,http://localhost//profiler/results-index? 即可看到監(jiān)測結(jié)果
總結(jié)
以上是生活随笔為你收集整理的MiniProfiler,一个.NET简单但有效的微型分析器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何解决在ASP.NET Core中找不
- 下一篇: 龙芯.NET正式发布 稳步推进生态建设