Logging is an essential part of modern application development. It helps in monitoring, debugging, and tracking the behavior of your applications. However, logging can also introduce runtime overhead, especially when done inefficiently. In this post we will learn what source generated logs are and how they can enhance the performance of your application.

What Are Source-Generated Logs?

.NET source generators are a feature that allows developers to inject code during compilation. Essentially, instead of writing boilerplate or repetitive code manually, source generators create that code for you at build time.

Source-generated logging builds upon this idea by generating log messages and methods during compile time, making logging more performant by removing the overhead associated with traditional logging methods (params keyword says hello).

This shift from runtime to compile-time log generation helps:

  • Minimize overhead in the execution path.
  • Reduce memory allocations due to the absence of runtime-generated strings.
  • Ensure logs are structured in a consistent manner.

Why Use Source-Generated Logs?

Traditional logging, particularly when using high-level frameworks like Microsoft.Extensions.Logging, often involves string formatting, reflection, and dynamic log message generation at runtime. These operations are not free and can cause:

  • Unnecessary allocations.
  • Performance penalties due to runtime string interpolations.
  • Potential bugs and typos in manually constructed log messages.

Source-generated logs solve these issues by generating the required code at compile-time. This results in:

  • Reduced memory allocation (since it avoids string interpolation).
  • Faster execution (no reflection or dynamic log generation).
  • Type-safety (ensuring logging message structure is validated at compile time).

Examples

Let’s see how you can implement source-generated logging in a .NET 6 or later project.

public static partial class LoggerMessageDefinitions
{
    [LoggerMessage(EventId = EventIdConstants.InfoUserLogin, Level = LogLevel.Information, Message = "User {UserId} has logged in.")]
    public static partial void LogUserLogin(this ILogger logger, int userId);

    [LoggerMessage(EventId = EventIdConstants.ErrorUserLogin, Level = LogLevel.Error, Message = "Error occurred while processing request.")]
    public static partial void LogError(this ILogger logger);
}

public class LoggingExample
{
    private readonly ILogger<LoggingExample> _logger;

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

    public void Example()
    {
        _logger.LogUserLogin(1);
        _logger.LogError();
    }
}
public static class EventIdConstants
{
    public const int InfoUserLogin = 1001;
    public const int ErrorUserLogin = 1002;
}

In this code:

  • We’re using the LoggerMessage attribute to define our logs.
  • Each log message is associated with a unique EventId and log level.
  • The partial keyword hints that the source generator will generate the rest of the logging method during compilation.

When compiled, the source generator will create the actual logging methods, removing the need for dynamic message formatting and improving performance.

When to Use Source-Generated Logs

Source-generated logging is particularly beneficial in high-performance applications, microservices, and systems where logging overhead can impact throughput. For instance:

  • Real-time applications where low-latency is crucial.
  • Cloud services where performance and cost-efficiency are key.
  • Large-scale systems where log volume is massive, and you need to optimize for resource usage.

However, for simpler applications where performance is less critical, traditional logging is still be easier to work with.

Conclusion

Source-generated logging is an excellent addition to the .NET ecosystem, helping developers optimize logging without sacrificing flexibility or readability. They are an easy win when it comes to optimizing performance. Please consider using them especially when you are in the cloud.

Affiliate promo

If you love learning new stuff and want to support me, consider buying a course from Dometrain using this link: Browse courses – Dometrain. Thank you!

Leave a comment

Trending