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 What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos