如何在 ASP.Net Core 中使用 LoggerMessage
ASP.NET Core 是一個(gè)開(kāi)源的、跨平臺(tái)的、輕量級(jí)模塊化框架,可用于構(gòu)建高性能、可伸縮的web應(yīng)用程序,你也許不知道 ASP.NET Core 中有一個(gè)藏得很深,而且非常強(qiáng)大的特性,那就是 LoggerMessage,與內(nèi)建的 Logger 相比,前者具有更高的性能,這篇文章我們來(lái)一起討論 LoggerMessage 到底能帶來(lái)什么好處,以及如何在 ASP.NET Core 3.0 中使用 LoggerMessage 。
LoggerMessage VS Logger
與內(nèi)置的 Logger 相比,LoggerMessage提供了以下幾個(gè)優(yōu)點(diǎn)。
性能
LoggerMessage 比 Logger 具有更少的對(duì)象分配和計(jì)算開(kāi)銷(xiāo),內(nèi)建的 Logger 有裝箱操作,而 LoggerMessage 巧妙的利用了靜態(tài)字段,靜態(tài)方法,以及具有強(qiáng)類(lèi)型擴(kuò)展方法來(lái)避免裝箱開(kāi)銷(xiāo)。
解析
與 Logger 相比,LoggerMessage 的解析機(jī)制更加高效,Logger 會(huì)在每次寫(xiě)入消息的時(shí)候都要解析模板,而 LoggerMessage 只需在消息定義的時(shí)候解析一次。
使用 LoggerMessage.Define 方法
在 Microsoft.Extensions.Logging 命名空間下的 LoggerMessage.Define 方法可用于高性能的記錄日志,要使用這個(gè)方法,需要指定正確的強(qiáng)類(lèi)型參數(shù)。
下面是 LoggerHelper.Define 源碼定義

接下來(lái)我們看一下如何使用 LoggerMessage.Define 方法,先定義一個(gè)靜態(tài)的 LoggerExtensions 類(lèi),如下代碼所示:
internal?static?class?LoggerExtensions
{
}
接下來(lái)創(chuàng)建一個(gè)用來(lái)記錄日志的擴(kuò)展方法,內(nèi)部使用的是 LoggerMessage.Define 方法,代碼如下:
????internal?static?class?LoggerExtensions
????{
???????public?static?void?RecordNotFound(this?ILogger?logger,?int?id)?=>?NotFound(logger,?id,?null);
???????
???????private?static?readonly?Actionint,?Exception>?NotFound?=?LoggerMessage.Define<int>?(LogLevel.Error,?new?EventId(1234,?nameof(NotFound)),"The?record?is?not?found:?{Id}");
????}
Action 中使用 LoggerMessage
接下來(lái)在項(xiàng)目默認(rèn)的 HomeController.Index() 方法中使用剛才創(chuàng)建的日志擴(kuò)展方法,如下代碼所示:
????public?class?HomeController?:?Controller
????{
????????private?readonly?ILogger?_logger;
????????public?HomeController(ILogger?logger )
????????{
????????????_logger?=?logger;
????????}
????????public?IActionResult?Index()
????????{
????????????_logger.RecordNotFound(1);
????????????return?View();
????????}
????}
????internal?static?class?LoggerExtensions
????{
????????public?static?void?RecordNotFound(this?ILogger?logger,?int?id)?=>?NotFound(logger,?id,?null);
????????private?static?readonly?Actionint,?Exception>?NotFound?=?LoggerMessage.Define<int>(LogLevel.Error,?new?EventId(1234,?nameof(NotFound)),?"The?record?is?not?found:?{Id}");
????}

LoggerMessage.Define 可以用來(lái)創(chuàng)建能夠緩沖日志消息的委托,這種方法相比內(nèi)建的 Logger 具有更高的性能,最后你可以在 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/loggermessage?view=aspnetcore-3.1 ?上了解更多關(guān)于 LoggerMessage 的知識(shí)。
譯文鏈接:https://www.infoworld.com/article/3535790/how-to-use-loggermessage-in-aspnet-core-30.html
