Edit

Share via


CA1848: Use the LoggerMessage delegates

Property Value
Rule ID CA1848
Title Use the LoggerMessage delegates
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 No

Cause

Use of logger extension methods, such as LogInformation and LogDebug.

Rule description

For high-performance logging scenarios, use the LoggerMessage pattern instead of Logger<T> extension methods.

How to fix violations

Use LoggerMessageAttribute to fix violations of this rule. (Or, if you're using .NET 5 or earlier, use the LoggerMessage class.)

public class SomethingDoer
{
   private readonly ILogger _logger;
   public SomethingDoer(ILogger<SomethingDoer> logger)
   {
       _logger = logger;
   }

   public void DoSomething()
   {
       // This call violates CA1848.
       _logger.LogInformation("Did something!");
   }
}

The following code fixes the violation.

public partial class SomethingDoer
{
   private readonly ILogger _logger;
   public SomethingDoer(ILogger<SomethingDoer> logger)
   {
       _logger = logger;
   }

   public void DoSomething()
   {
       Log_DidSomething();
   }

   [LoggerMessage(Level = LogLevel.Information, Message = "Did something!")]
   private partial void Log_DidSomething();
}

LoggerMessage provides the following performance advantages over Logger<T> extension methods:

  • Logger extension methods require "boxing" (converting) value types, such as int, into object. The LoggerMessage pattern avoids boxing by using static Action fields and extension methods with strongly typed parameters.
  • Logger extension methods must parse the message template (named format string) every time a log message is written. LoggerMessage only requires parsing a template once when the message is defined.

When to suppress warnings

Do not suppress a warning from this rule.

See also