.NET 6 引入了 LoggerMessageAttribute 类型。 使用时,它会以source-generators的方式生成高性能的日志记录 API。

source-generators可在编译代码时,可以提供其他源代码作为编译的输入。

LoggerMessageAttribute依赖于 ILogger 接口和 LoggerMessage.Define 功能。

在 partial 日志记录方法上使用 LoggerMessageAttribute 时,系统会触发源生成器。 触发后,它既可以自动生成其修饰的 partial 方法的实现,也可以生成包含正确用法提示的编译时诊断。

与现有的日志记录方法相比,编译时日志记录解决方案在运行时通常要快得多。 这是因为它最大限度地消除了装箱、临时分配和副本。

 

基本用法

使用 LoggerMessageAttribute 时,类和方法必须为 partial。 真实记录日志的代码生成器在编译时触发,并生成 partial 方法的实现。

public static partial class Log
{
    [LoggerMessage(
        EventId = 0,
        Level = LogLevel.Error,
        Message = "Can not open SQL connection {err}")]
    public static partial void CouldNotOpenConnection(this ILogger logger, string err);
}

在上面的示例中,日志记录方法为 static,日志级别在属性定义中指定,并使用 this 关键字将方法定义为扩展方法。

在调用时,可按常规方式调用即可

internal class Program
{
    private static async Task Main(string[] args)
    {

        using ILoggerFactory loggerFactory = LoggerFactory.Create(
            builder =>
            builder.AddJsonConsole(
                options =>
                options.JsonWriterOptions = new JsonWriterOptions()
                {
                    Indented = true
                }));

        ILogger logger = loggerFactory.CreateLogger("Program");

        logger.CouldNotOpenConnection("network err");
    }
}

 

使用规则

在日志记录方法上使用 LoggerMessageAttribute 时,必须遵循一些规则:

  • 日志记录方法必须为 partial 并返回 void。
  • 日志记录方法名称不得以下划线开头。
  • 日志记录方法的参数名称不得以下划线开头。
  • 日志记录方法不得在嵌套类型中定义。
  • 日志记录方法不能是泛型方法。
  • 如果日志记录方法是 static,则需要 ILogger 实例作为参数。

代码生成模型依赖于使用新式 C# 编译器 9 或更高版本编译的代码。 .NET 5 提供了 C# 9.0 编译器。 若要升级到新式 C# 编译器,请编辑项目文件以面向 C# 9.0。 

 

好处

使用源生成器方法有几个主要好处:

  • 允许保留日志记录结构,并启用消息模板所需的确切格式语法。
  • 允许为模板占位符提供替代名称,允许使用格式说明符。
  • 允许按原样传递所有原始数据,在对其进行处理之前,不需要进行任何复杂的存储(除了创建 string)。
  • 提供特定于日志记录的诊断,针对重复的事件 ID 发出警告。

 

https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/

https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/partial-method

https://learn.microsoft.com/zh-cn/dotnet/core/extensions/logger-message-generator

posted on 2024-03-15 09:50  chester·chen  阅读(422)  评论(1编辑  收藏  举报