Microsoft.Extensions.Logging.ILogger<T>
和 消息模板 进行结构化日志记录时,Visual Studio 会突出显示消息模板“命名孔”/参数,如下所示(请参阅 {Address}
):
是否可以在自己的方法的调用处实现同样的高亮效果?
如果是这样,怎么办?突出显示背后的机制是什么?
背景(但我对一般情况很好奇):
我们正在使用异常过滤方法如此处讨论的那样,如下所示:
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;
}
// ...
}
但是,使用此扩展方法时,不会突出显示正在使用消息模板:
事实证明,是 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;
}
使它看起来像这样:
我忍不住想知道是什么让 Resharper 对 Microsoft ILogger 成员进行突出显示...