使用 MiniProfiler 來分析 ASP.NET Core 應(yīng)用

使用 MiniProfiler 來分析 ASP.NET Core 應(yīng)用

MiniProfiler(https://miniprofiler.com/)是一個(gè)輕量級且簡單易用的分析工具庫,它可以用來分析ASP.NET Core應(yīng)用。

優(yōu)點(diǎn)

針對ASP.NET Core MVC應(yīng)用,使用MiniProfiler的優(yōu)點(diǎn)是:它會把結(jié)果直接放在頁面的左下角,隨時(shí)可以點(diǎn)擊查看;這樣的話就可以感知出你的程序運(yùn)行的怎么樣;同時(shí)這也意味著,在你開發(fā)新功能的同時(shí),可以很快速的得到反饋。

一、安裝配置MiniProfiler

在現(xiàn)有的ASP.NET Core MVC項(xiàng)目里,通過Nuget安裝MiniProfiler :

Install-Package MiniProfiler.AspNetCore.Mvc

當(dāng)然也可以通過Nuget Package Manager可視化工具安裝

01.png

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

第一步,來到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);

        // 當(dāng)然這個(gè)方法還可以添加一個(gè)lambda表達(dá)式作為參數(shù),從而做一些自定義的配置:
        services.AddMiniProfiler(options =>
        {
            // 設(shè)定彈出窗口的位置是左下角
            options.PopupRenderPosition = RenderPosition.BottomLeft;
            // 設(shè)定在彈出的明細(xì)窗口里會顯式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)
    {
        ...

        // 最重要的一點(diǎn)是就是配置中間件在管道中的位置,一定要把它放在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>

    @* 其實(shí)放在頁面的任意地方都應(yīng)該可以,但是由于它會加載一些腳本文件,所以建議放在footer下面: *@@* 其實(shí)放在頁面的任意地方都應(yīng)該可以,但是由于它會加載一些腳本文件,所以建議放在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>

運(yùn)行應(yīng)用,可以看到左下角就是MiniProfiler:

02.png

點(diǎn)擊它之后會彈出窗口,里面有每個(gè)步驟具體的耗用時(shí)間。

03.png

二、MiniProfiler 具體使用

分析局部代碼

前面的例子里,我們使用MiniProfiler分析了頁面整個(gè)流程的時(shí)間。而MiniProfiler也可以用來分析一段代碼所耗用的時(shí)間??蠢樱?/p>

    public async Task<IActionResult> Index()
    {
#if !DEBUG
        // 這里我們使用了using語句,里面使用了 MiniProfiler 類的 Current 屬性,在該屬性上面有一個(gè)Step()方法,
        // 它可以用來分析using語句里面的代碼,在Step方法里,要提供一個(gè)具有描述性的名稱來表示該段代碼做的是什么動(dòng)作,這個(gè)名稱會顯示在結(jié)果里。
        using (MiniProfiler.Current.Step("計(jì)算第一步"))
        {
            var users = await _context.Users.ToListAsync();
            return View(users);
        }
#else
        // 通常,我會使用 using 語句塊來嵌套著使用

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

            // ... 相關(guān)操作
            Thread.Sleep(30);

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

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

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


    04.png
  • 使用 Inline() 方法結(jié)果展示:


    05.png

自定義分析 CustomTiming

有時(shí)候,分析一些例如請求外部動(dòng)作的時(shí)候,上面講的做法可能不太靈光,這里我們就可以使用CustomTime()方法

    public async Task<IActionResult> Privacy()
    {
        // 這個(gè)例子里,我們使用 MiniProfiler.Current.CustomTiming() 方法。
        //  第一個(gè)參數(shù)是一個(gè)用于分類的字符串,這里我用的是http請求,所以寫了http;
        //  第二個(gè)參數(shù)是命令字符串,這里我用不上,暫時(shí)留空;
        //  第三個(gè)參數(shù)是執(zhí)行類型,這里我用的是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();
    }
  • 運(yùn)行程序,可以看到窗口的右側(cè)出現(xiàn)了http這一列:
06.png
  • 點(diǎn)擊 http 所在列的153.1 (1),這就是使用CustomTiming分析的那段代碼,它請求的URL和返回碼都顯示了出來。
07.png

三、案例源碼:

MiniProfilerCoreDemo
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容