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 feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos