MiniProfiler性能分析工具— .Net Core中用法

前言:

 在日常開發中,應用程序的性能是我們需要關注的一個重點問題。當然我們有很多工具來分析程序性能:如:Zipkin等;但這些過於複雜,需要單獨搭建。

 MiniProfiler就是一款簡單,但功能強大的應用新能分析工具;可以幫助我們定位:SQL性能問題、響應慢等問題。

 本篇文章將介紹MiniProfiler在Asp.Net Core中如何使用

一、MiniProfiler介紹

  MiniProfiler是一款針對.NET, Ruby, Go and Node.js的性能分析的輕量級程序。可以對一個頁面本身,及該頁面通過直接引用、Ajax、Iframe形式訪問的其它頁面進行監控,監控內容包括數據庫內容,並可以顯示數據庫訪問的SQL(支持EF、EF CodeFirst等 )。並且以很友好的方式展現在頁面上。

    MiniProfiler官網://miniprofiler.com/

    MiniProfiler的一個特別有用的功能是它與數據庫框架的集成。除了.NET原生的 DbConnection類,MiniProfiler還內置了對實體框架(Entity Framework)以及LINQ to SQL、RavenDb和MongoDB的支持。任何執行的Step都會包括當時查詢的次數和所花費的時間。為了檢測常見的錯誤,如N+1反模式,profiler將檢測僅有參數值存在差異的多個查詢。

二、MiniProfiler用法

 1、Nuget包安裝:

//Mvc
Install-Package MiniProfiler.AspNetCore.Mvc
//EF分析添加
Install-Package MiniProfiler.EntityFrameworkCore

 2、配置MiniProfiler:修改Startup.cs

  a) 注入MiniProfiler

public void ConfigureServices(IServiceCollection services)
{
    // ...其他配置...

    // 注入MiniProfiler
    services.AddMiniProfiler(options =>
    {
        //訪問地址路由根目錄;默認為:/mini-profiler-resources
        options.RouteBasePath = "/profiler";
        //數據緩存時間
        (options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromMinutes(60);
        //sql格式化設置
        options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter();
        //跟蹤連接打開關閉
        options.TrackConnectionOpenClose = true;
        //界面主題顏色方案;默認淺色
        options.ColorScheme = StackExchange.Profiling.ColorScheme.Dark;
        //.net core 3.0以上:對MVC過濾器進行分析
        options.EnableMvcFilterProfiling = true;
        //對視圖進行分析
        options.EnableMvcViewProfiling = true;

        //控制訪問頁面授權,默認所有人都能訪問
        //options.ResultsAuthorize;
        //要控制分析哪些請求,默認說有請求都分析
        //options.ShouldProfile;

        //內部異常處理
        //options.OnInternalError = e => MyExceptionLogger(e);
    })
    // AddEntityFramework是要監控EntityFrameworkCore生成的SQL
    .AddEntityFramework();
}

  b) 啟用MiniProfiler  

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMemoryCache cache)
{
    // ...其他配置

    //該方法必須在app.UseEndpoints以前
    app.UseMiniProfiler();

    app.UseEndpoints(routes =>
    {
        // ...
    });
}

  c) MVC項目:

   修改 _ViewImports.cshtml    

@using StackExchange.Profiling
@addTagHelper *, MiniProfiler.AspNetCore.Mvc

   將MiniProfiler添加到布局文件(Shared/_Layout.cshtml)中

<mini-profiler />

  d) 運行效果:

 

三、 Swagger UI接入MiniProfiler

 使用步驟和前面大體一樣

 1、下載Swagger頁面:

  請先在Github中下載對應版本的swagger頁面://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/index.html

 2、添加到項目中,並設置index.html為:內嵌資源

  

  3、修改UseSwaggerUI中間件的配置

app.UseSwaggerUI(c =>
{
    //AuditLogDemo項目命名空間
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "AuditLogDemo API V1");
    c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("AuditLogDemo.wwwroot.index.html");
});

  4、獲取MiniProfiler的html代碼片段 

/// <summary>
/// 獲取html片段
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("GetHtml")]
public IActionResult GetHtml()
{
    var html = MiniProfiler.Current.RenderIncludes(HttpContext);
    return Ok(html.Value);
}

  

 5、在Swagger的Html中添加獲取的MiniProfiler片段

<!-- HTML for static distribution bundle build -->
<script async="async" id="mini-profiler" src="/profiler/includes.min.js?v=4.2.22+4563a9e1ab" 
        data-version="4.2.22+4563a9e1ab" data-path="/profiler/" 
        data-current-id="0601948b-d995-4a86-9cae-33d73ecd2f59" 
        data-ids="0601948b-d995-4a86-9cae-33d73ecd2f59" 
        data-position="Left" 
        data-scheme="Dark" 
        data-authorized="true" 
        data-max-traces="15" 
        data-toggle-shortcut="Alt+P" 
        data-trivial-milliseconds="2.0" 
        data-ignored-duplicate-execute-types="Open,OpenAsync,Close,CloseAsync"></script>

<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>%(DocumentTitle)</title>
    ……

 6、調用效果:

  

 

   如上圖可以查看到所有請求路徑及Sql操作耗時,那麼如果需要監控指定代碼塊耗時如何實現呢

四、自定義標記:

   1、添加標記代碼:

var miniPro = MiniProfiler.Current;
using (miniPro.Step("Add AuditLog"))
{
    //保存審計日誌
    await _auditLogService.SaveAsync(auditInfo);
}

  

  2、取消監控方式:  

using(MiniProfiler.Current.Ignore())
{
   //代碼     
}

 3、當然MiniProfiler還有很多其他功能等待解鎖:如監控ADO.NET執行耗時,需要使用:ProfileDBConnection 和 ProfileDBCommand對象:

總結:

 1、MiniProfiler使用非常簡單
 2、功能滿足日常中程序性能優化相關問題

其他: 

 MiniProfiler的監控列表地址://{xxx}/profiler/results-index