结构化登录如何实现消息模板高亮?

问题描述 投票:0回答:1

当使用

Microsoft.Extensions.Logging.ILogger<T>
消息模板 进行结构化日志记录时,Visual Studio 会突出显示消息模板“命名孔”/参数,如下所示(请参阅
{Address}
):

Message template with highlighting

是否可以在自己的方法的调用处实现同样的高亮效果?

如果是这样,怎么办?突出显示背后的机制是什么?


背景(但我对一般情况很好奇):

我们正在使用异常过滤方法如此处讨论的那样,如下所示:

public static class LoggerExtensions
{
    public static bool LogExceptionNoCatch<T>(this ILogger<T> logger, Exception exception, string? message, params object?[] args)
    {
        logger.LogError(exception, message, args);
        return false;
    }
    // ...
}

但是,使用此扩展方法时,不会突出显示正在使用消息模板:

Message template withoud highlighting

c# .net visual-studio structured-logging
1个回答
0
投票

事实证明,是 Resharper 为我做了突出显示,正如 @Sinatr 的评论中所建议的。 (我应该在发帖之前检查一下。)

在消息参数中添加 StructuredMessageTemplateAttribute 可在调用站点添加突出显示。

public static bool LogExceptionNoCatch<T>(this ILogger<T> logger, Exception exception, [JetBrains.Annotations.StructuredMessageTemplate] string? message, params object?[] args)
{
    logger.LogError(exception, message, args);
    return false;
}

使它看起来像这样:

Method call with method template highlighting

我忍不住想知道是什么让 Resharper 对 Microsoft ILogger 成员进行突出显示...

© www.soinside.com 2019 - 2024. All rights reserved.