Skip to content

ASP.NET Fast and Performant Logging

ASP.NET Fast and Performant Logging
Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

In this blog post, we will discuss how to implement fast and performant logging in ASP.NET. When developing an ASP.NET, logging is an essential aspect that can help developers debug and monitor their application’s performance. However, logging can also slow down the application’s performance if not implemented correctly. By the way, did you know that we offer a unique and powerful online course that boosts your C# career? Check it out here!

Step 1: Define The Logger Class

Define a static class to hold the logging messages:

public static partial class Log
{
    [LoggerMessage(20, LogLevel.Information, "Weather forecast requested at {date}.")]
    public static partial void WeatherForecastRequested(this ILogger logger, DateTime date);
}

Notice that the class and the method are both partial.

 

Step 2: Use the Logger Class

Inject the ILogger into a controller and call the method. Since I’ve created

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        _logger.WeatherForecastRequested(DateTime.Now);

        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

Following these steps, you can implement fast and performant logging using `LoggerMessageAttribute` in your ASP.NET applications.

 

Step 3: Run It

Navigate to `http://localhost:5054/WeatherForecast` where `5054` is your application’s port. Then you should see a log like the following on the console:

info: PerformantLogging.Controllers.WeatherForecastController[20]
      Weather forecast requested at 03/07/2023 15:10:08.

 

The following map illustrates the role of each parameter.

ASP.NET Fast and Performant Logging

The technique we used for logging is so-called Source-Generated Logging. Let’s see how it works under the hood.

 

Source-Generation Logging

Source-generation logging is a new feature introduced in C# 9.0 that uses source generators to create optimized logging code at compile-time.

 

When you compile the app, the source generators read the source code and generate additional source code based on that information. This generated code is then compiled along with the original source code to produce the final executable. In the case of logging, the source generators read the logging methods defined with LoggerMessageAttribute and generate optimized logging code based on that information.

 

By defining logging messages with LoggerMessageAttribute, developers can create a clean and maintainable logging system that has minimal impact on performance. This is particularly important in high-performance scenarios such as web applications, where logging can have a significant impact on application performance. Using LoggerMessageAttribute with C# source generators provides a powerful and efficient way to implement logging in .NET because it is created at compile-time rather than runtime.

LoggerMessageAttribute

The LoggerMessageAttribute contains metadata about the log message, including the message template, log level, and an event ID. This metadata is used by the source generator to create a method that will execute the logging statement. By using the source generation technique, we can define logging messages statically at compile-time, which enables the logging system to use a lightweight and fast code path, improving application performance.

 

Conclusion

Using source generation logging is a powerful technique that enables developers to create fast and efficient logging systems with minimal impact on performance. It allows developers to create a clean and maintainable logging system that is easy to read and maintain. Following the steps outlined in this blog post and using LoggerMessageAttribute with C# source generators, you can implement fast and performant logging in your .NET applications. You can also read this article to learn how to log exceptions in C#. If you want to skyrocket your C# career, check out our powerful ASP.NET full-stack web development course that also covers test-driven development.

 

 

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide