79466039

Date: 2025-02-25 09:42:33
Score: 1.5
Natty:
Report link

Thanks to Richard for pointing me in the right direction here.

I ended up implementing this by creating a custom attribute like so (NB - namespace is unimportant, but the class name must be this specifically):

[AttributeUsage(AttributeTargets.Method)]
public sealed class MessageTemplateFormatMethodAttribute: Attribute
{
    public string FormatParameterName { get; }

    public MessageTemplateFormatMethodAttribute(string formatParameterName)
    {
        FormatParameterName = formatParameterName;
    }
}

This can then be used on a method, passing in the nameof the string parameter:

public static class ILoggerExtensions
{
    [MessageTemplateFormatMethodAttribute(nameof(message))]
    public static void LogCustom(this ILogger logger, string? message, params object?[] args)
    {
        logger.LogDebug(message, args);
    }
}

This gives us support in the IDE:

ReSharper analysers at work in Visual Studio

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Josh Brunton