Search code examples
c#.netvisual-studiostructured-logging

How to achieve message template highlighting for structured logging?


When using the Microsoft.Extensions.Logging.ILogger<T> with message templates for structured logging, Visual Studio highlights the message template "named holes"/parameters like this (see {Address}):

Message template with highlighting

Is it possible to achieve the same highlighting effect at the call site for one of your own methods?

If so, how? What are the mechanics behind the highlighting?


Background (but I'm curius in the general case):

We're using an exception filter method as discussed here, like this:

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;
    }
    // ...
}

However, when using this extension method there is no highlighting indicating that message templates is being used:

Message template withoud highlighting


Solution

  • It turns out that it is Resharper that does the highlighting for me, as suggested in a comment by @Sinatr. (I should have checked before posting.)

    Adding the Jetbrains' StructuredMessageTemplateAttribute at the message parameter adds highlighting at the call site.

    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;
    }
    

    so that it looks like this:

    Method call with method template highlighting

    I can't help wondering what makes Resharper do highlighting on the Microsoft ILogger members though...