overview
ℹ️ Important
Availability: .NET 6
Documentation: https://learn.microsoft.com/en-us/dotnet/core/extensions/logger-message-generator
The LoggerMessageAttribute, part of Microsoft.Extensions.Logging, source-generates performant logging APIs. The auto-generated code relies on ILogger and LoggerMessage.Define.
This implementation is significantly faster than other approaches).
usage
Use LoggerMessageAttribute on partial logging methods:
public static partial class Log
{
    [LoggerMessage(
        EventId = 0,
        Level = LogLevel.Critical,
        Message = "Could not open socket to `{hostName}`")]
    public static partial void CouldNotOpenSocket(ILogger logger, string hostName);
}
The method does not have to be static. Example on an instance method:
public partial class InstanceLoggingExample
{
    private readonly ILogger _logger;
    public InstanceLoggingExample(ILogger logger)
    {
        _logger = logger;
    }
    [LoggerMessage(
        EventId = 0,
        Level = LogLevel.Critical,
        Message = "Could not open socket to `{hostName}`")]
    public partial void CouldNotOpenSocket(string hostName);
}
The log level can also be dynamically set:
public static partial class Log
{
    [LoggerMessage(
        EventId = 0,
        Message = "Could not open socket to `{hostName}`")]
    public static partial void CouldNotOpenSocket(
        ILogger logger,
        LogLevel level, /* Dynamic log level as parameter, rather than defined in attribute. */
        string hostName);
}
logging message constraints
Logging methods must adhere to these constraints:
- They must be partialand returnvoid
- Their names cannot start with an underscore
- Their parameter names cannot start with an underscore
- They cannot be defined in a nested type
- They cannot be generic