如何在 ASP.Net Core 中使用 LoggerMessage
ASP.NET Core 是一個開源的、跨平臺的、輕量級模塊化框架,可用于構(gòu)建高性能、可伸縮的web應(yīng)用程序,你也許不知道 ASP.NET Core 中有一個藏得很深,而且非常強(qiáng)大的特性,那就是 LoggerMessage,與內(nèi)建的 Logger 相比,前者具有更高的性能,這篇文章我們來一起討論 LoggerMessage 到底能帶來什么好處,以及如何在 ASP.NET Core 3.0 中使用 LoggerMessage 。
LoggerMessage VS Logger
與內(nèi)置的 Logger 相比,LoggerMessage提供了以下幾個優(yōu)點。
- 性能
LoggerMessage 比 Logger 具有更少的對象分配和計算開銷,內(nèi)建的 Logger 有裝箱操作,而LoggerMessage 巧妙的利用了靜態(tài)字段,靜態(tài)方法,以及具有強(qiáng)類型擴(kuò)展方法來避免裝箱開銷。
- 解析
與 Logger 相比,LoggerMessage 的解析機(jī)制更加高效,Logger 會在每次寫入消息的時候都要解析模板,而 LoggerMessage 只需在消息定義的時候解析一次。
使用 LoggerMessage.Define 方法
在 Microsoft.Extensions.Logging 命名空間下的 LoggerMessage.Define
下面是 LoggerHelper.Define
接下來我們看一下如何使用 LoggerMessage.Define 方法,先定義一個靜態(tài)的 LoggerExtensions 類,如下代碼所示:
- internal static class LoggerExtensions
- {
- }
接下來創(chuàng)建一個用來記錄日志的擴(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 Action<ILogger, int, Exception> NotFound = LoggerMessage.Define<int> (LogLevel.Error, new EventId(1234, nameof(NotFound)),"The record is not found: {Id}");
- }
Action 中使用 LoggerMessage
接下來在項目默認(rèn)的 HomeController.Index() 方法中使用剛才創(chuàng)建的日志擴(kuò)展方法,如下代碼所示:
- public class HomeController : Controller
- {
- private readonly ILogger<HomeController> _logger;
- public HomeController(ILogger<HomeController> 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 Action<ILogger, int, Exception> NotFound = LoggerMessage.Define<int>(LogLevel.Error, new EventId(1234, nameof(NotFound)), "The record is not found: {Id}");
- }
LoggerMessage.Define 可以用來創(chuàng)建能夠緩沖日志消息的委托,這種方法相比內(nèi)建的 Logger 具有更高的性能,最后你可以在 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/loggermessage?view=aspnetcore-3.1 上了解更多關(guān)于 LoggerMessage 的知識。
譯文鏈接:https://www.infoworld.com/article/3535790/how-to-use-loggermessage-in-aspnet-core-30.html