使用 MiniProfiler 來分析 ASP.NET Core 應用

使用 MiniProfiler 來分析 ASP.NET Core 應用

MiniProfiler(https://miniprofiler.com/)是一個輕量級且簡單易用的分析工具庫,它能夠用來分析ASP.NET Core應用。html

優勢

針對ASP.NET Core MVC應用,使用MiniProfiler的優勢是:它會把結果直接放在頁面的左下角,隨時能夠點擊查看;這樣的話就能夠感知出你的程序運行的怎麼樣;同時這也意味着,在你開發新功能的同時,能夠很快速的獲得反饋。jquery

1、安裝配置MiniProfiler

在現有的ASP.NET Core MVC項目裏,經過Nuget安裝MiniProfiler :git

Install-Package MiniProfiler.AspNetCore.Mvcgithub

固然也能夠經過Nuget Package Manager可視化工具安裝json

01.png

接下來配置MiniProfiler,總共分三步:bootstrap

第一步,來到Startup.csConfigureServices方法裏,添加services.AddMiniProfiler();

// This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        // 固然這個方法還能夠添加一個lambda表達式做爲參數,從而作一些自定義的配置:
        services.AddMiniProfiler(options =>
        {
            // 設定彈出窗口的位置是左下角
            options.PopupRenderPosition = RenderPosition.BottomLeft;
            // 設定在彈出的明細窗口裏會顯式Time With Children這列
            options.PopupShowTimeWithChildren = true;
        });
    }

第二步,來到來到Startup.csConfigure方法裏,添加app.UseMiniProfiler();

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        ...

        // 最重要的一點是就是配置中間件在管道中的位置,必定要把它放在UseMvc()方法以前。 
        app.UseMiniProfiler();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

第三步,將MiniProfilerTag Helper放到頁面上

  • _ViewImports 頁面引入 MiniProfiler 的 Tag Helper :
...

    @using StackExchange.Profiling

    ...
    @addTagHelper *, MiniProfiler.AspNetCore.Mvc
  • 將 MiniProfiler 的Tag Helper 放入 _Layout.cshtml 中:
...

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2019 - MiniProfilerCoreDemo - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>

    @* 其實放在頁面的任意地方都應該能夠,可是因爲它會加載一些腳本文件,因此建議放在footer下面: *@@* 其實放在頁面的任意地方都應該能夠,可是因爲它會加載一些腳本文件,因此建議放在footer下面: *@
    <mini-profiler />

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
    </environment>

    ...

    @RenderSection("Scripts", required: false)
</body>
</html>

運行應用,能夠看到左下角就是MiniProfiler:cookie

02.png

點擊它以後會彈出窗口,裏面有每一個步驟具體的耗用時間。app

03.png

2、MiniProfiler 具體使用

分析局部代碼

前面的例子裏,咱們使用MiniProfiler分析了頁面整個流程的時間。而MiniProfiler也能夠用來分析一段代碼所耗用的時間。看例子:asp.net

public async Task<IActionResult> Index()
    {
#if !DEBUG
        // 這裏咱們使用了using語句,裏面使用了 MiniProfiler 類的 Current 屬性,在該屬性上面有一個Step()方法,
        // 它能夠用來分析using語句裏面的代碼,在Step方法裏,要提供一個具備描述性的名稱來表示該段代碼作的是什麼動做,這個名稱會顯示在結果裏。
        using (MiniProfiler.Current.Step("計算第一步"))
        {
            var users = await _context.Users.ToListAsync();
            return View(users);
        }
#else
        // 一般,我會使用 using 語句塊來嵌套着使用

        using(MiniProfiler.Current.Step("第1步"))
        {

            // ... 相關操做
            Thread.Sleep(30);

            using(MiniProfiler.Current.Step("第1.1步"))
            {
                // ... 相關操做
                Thread.Sleep(30);
            }

            using(MiniProfiler.Current.Step("第1.2步"))
            {
                // ... 相關操做
                Thread.Sleep(30);
            }
       }

        // 可是若是你只想分析一句話,那麼使用using語句就顯得太麻煩了,這種狀況下可使用 Inline() 方法:
        var users = await MiniProfiler.Current.Inline(async () => await _context.Users.ToListAsync(), "計算第一步");
        return View(users);
#endif
    }
  • 使用 using 語句塊嵌套結果展現:
    04.pngjsp

  • 使用 Inline() 方法結果展現:
    05.png

自定義分析 CustomTiming

有時候,分析一些例如請求外部動做的時候,上面講的作法可能不太靈光,這裏咱們就可使用CustomTime()方法

public async Task<IActionResult> Privacy()
    {
        // 這個例子裏,咱們使用 MiniProfiler.Current.CustomTiming() 方法。
        //  第一個參數是一個用於分類的字符串,這裏我用的是http請求,因此寫了http;
        //  第二個參數是命令字符串,這裏我用不上,暫時留空;
        //  第三個參數是執行類型,這裏我用的是Get請求,因此寫了GET;
        using (CustomTiming timing = MiniProfiler.Current.CustomTiming("http", string.Empty, "GET"))
        {
            var url = "http://27.24.159.155";
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri(url)
            };
            httpClient.DefaultRequestHeaders.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var response = await httpClient.GetAsync("/system/resource/code/news/click/dynclicks.jsp?clickid=1478&owner=1220352265&clicktype=wbnews");

            timing.CommandString = $"URL:{url}\n\r Response Code:{response.StatusCode}";

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Error fetching data from API");
            }

            var clickTimes = await response.Content.ReadAsStringAsync();

            ViewData["clickTimes"] = clickTimes;
        }

        return View();
    }
  • 運行程序,能夠看到窗口的右側出現了http這一列:

06.png

  • 點擊 http 所在列的153.1 (1),這就是使用CustomTiming分析的那段代碼,它請求的URL和返回碼都顯示了出來。

07.png

3、案例源碼:

MiniProfilerCoreDemo
相關文章
相關標籤/搜索