Take advantage of high-performance logging by using LoggerMessage instead of Logger extension methods in ASP.NET Core Credit: Loops7 / Getty Images ASP.NET Core is an open source, cross-platform, lean, and modular framework for building high-performance, scalable web applications. ASP.NET Core comes up with a built-in logging framework out-of-the-box. It is available as part of the Microsoft.Extensions.Logging namespace. One of the hidden but powerful features in ASP.NET Core is LoggerMessage, which has reduced overhead compared to the Logger extension methods. This article presents a discussion of the features and benefits of LoggerMessage and how we can work with LoggerMessage in ASP.NET Core 3.0. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here. Create an ASP.NET Core 3.0 API project First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Create. In the “Create New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top. I’ll be using ASP.NET Core 3.0 here. Select “API” as the project template to create a new ASP.NET Core API application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either. Click Create. This will create a new ASP.NET Core API project in Visual Studio. Select the Controllers solution folder in the Solution Explorer window and click “Add -> Controller…” to create a new controller named DefaultController. We’ll use this project in the subsequent sections of this article. LoggerMessage vs. Logger extension methods LoggerMessage provides the following benefits over Logger extension methods. Performance — Object allocations and computational overheads are reduced in LoggerMesage compared to the Logger extension methods. Logger extension methods have boxing overheads. LoggerMessage avoids boxing overheads by taking advantage of static action fields and extension methods that have strongly-typed parameters. Parsing — Parsing is more efficient in LoggerMessage compared to the Logger extension methods. Logger extension methods must parse the message template whenever a log message is written. LoggerMessage must parse a template only once — at the time when the message is defined. Use the LoggerMessage.Define method in ASP.NET Core The LoggerMessage.Define static method pertaining to the Microsoft.Extensions.Logging namespace can be used for high performant logging in .NET Core. When using this method, you will need to specify the strongly-typed parameters correctly. Here is what the LoggerHelper.Define method looks like: public static class LoggerMessage { public static Action<ILogger, T1, Exception> Define<T1>( LogLevel logLevel, EventId eventId, string formatString) { var formatter = CreateLogValuesFormatter( formatString, expectedNamedParameterCount: 1); return (logger, arg1, exception) => { if (logger.IsEnabled(logLevel)) { logger.Log(logLevel, eventId, new LogValues<T1>(formatter, arg1), exception, LogValues<T1>.Callback); } }; } } We’ll now explore how we can use the LoggerMessage.Define method. To do this, let’s create a static class named LoggerExtensions as shown below. internal static class LoggerExtensions { } Now create an extension method as well as an Action delegate to log data using the LoggerMessage.Define method as shown below. 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}"); } Use LoggerMessage in Action methods in ASP.NET Core Lastly, open the DefaultController class we created earlier and replace the default code with the action method shown in this section. The following code snippet illustrates how you can take advantage of the extension method we just created in your controller’s action methods. [HttpGet("{id}")] public async Task<ActionResult<Author>> Get(int id) { var author = await _context.Authors.FindAsync(id); if (author != null) { return author; } else { _logger.NotFound(id); return NotFound(); } } The LoggerMessage.Define method can be used to create delegates that can later be used to cache log messages with improved performance. Logging using LoggerMessage.Define is faster than using the Logger extension methods. The built-in logging framework in ASP.NET Core has been in use for quite some time. You can find the complete source code here. And you can learn more about LoggerMessage from Microsoft’s online documentation. Related content how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos