Joydip Kanjilal
Contributor

How to use LoggerMessage in ASP.NET Core 3.0

how-to
Apr 06, 20205 mins
C#Microsoft .NETSoftware Development

Take advantage of high-performance logging by using LoggerMessage instead of Logger extension methods in ASP.NET Core

Binary stream passing over rows of monitors, each also displaying binary streams.
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.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.
  7. 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.
  8. Select “API” as the project template to create a new ASP.NET Core API application.
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. 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

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author