MiniProfiler 是一款性能分析的輕量級程序,能夠基於action(request)記錄每一個階段的耗時時長,仍是能夠顯示訪問數據庫時的SQL等。html
企鵝號:877617006git
本篇主要介紹.Net Core 3.1下如何使用Swagger集成MiniProfiler來對咱們的WebAPI接口進行監控。github
Install-Package MiniProfiler.AspNetCore.Mvc Install-Package MiniProfiler.EntityFrameworkCore
MiniProfiler.EntityFrameworkCore 用來監控EF Core生成的SQL數據庫
在startup.cs 中配置服務ConfigureServicesjson
services.AddMiniProfiler(options => { options.RouteBasePath = "/profiler"; }).AddEntityFramework();
激活中間件,啓用MiniProfiler服務,放在UseEndpoints方法以前。app
app.UseMiniProfiler();
app.UseSwaggerUI(c => { c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("AdmBoots.Api.index.html"); c.RoutePrefix = string.Empty; c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });
注意:這裏AdmBoots.Api是項目的命名空間名
當前這個時候還不能使用,咱們還須要在 Swagger的index.html中進行配置,以便它能在 Swagger 中使用。
重點來了
咱們首先須要獲取用於顯示MiniProfiler的html代碼片斷,隨便寫個控制器,使用MiniProfiler的API輸出一下就能夠了。async
[HttpGet] public IActionResult GetCounts() { var html = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext); return Ok(html.Value); }
你也能夠將var html = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext);隨便找個地方寫一下,而後經過斷點的方式獲取html代碼片斷。
而後咱們將生成的內容拷貝出來粘貼在Swagger的index.html頂部性能
<!-- HTML for static distribution bundle build --> <script async="async" id="mini-profiler" src="/profiler/includes.min.js?v=4.2.1+b27bea37e9" data-version="4.2.1+b27bea37e9" data-path="/profiler/" data-current-id="142f3c02-c5d7-42e0-be9e-2a45e46d727a" data-ids="64b457a1-275e-4bfa-9b2f-e5bd5385a80f,142f3c02-c5d7-42e0-be9e-2a45e46d727a" data-position="Left" data-scheme="Light" 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> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>%(DocumentTitle)</title> ........ ........
從新啓動項目,Swagger文檔頁面的左上角就出現了一個小的面板,當請求接口以後,會顯示出當前請求的分析數據。(若是項目啓動後,左上角小面板沒出來,點請求接口後就會出來了)
這樣咱們就能夠查看咱們接口的耗時及SQL了。這裏的SQL仍是爲咱們拼接好參數的,很是的方便。ui
依賴注入code
private readonly IHttpContextAccessor _accessor; public ChartController(IHttpContextAccessor accessor) { _accessor = accessor; }
在Startup.cs中將IHttpContextAccessor注入容器
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();