C#idiomatic C#
ca1848fundamentals/code-analysis/quality-rules

Code analysis

CA1848: Use the LoggerMessage delegates

Learn about code analysis rule CA1848: Use the LoggerMessage delegates

CA1848 Performance enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

Use of logger extension methods, such as Microsoft.Extensions.Logging.LoggerExtensions.LogInformation and Microsoft.Extensions.Logging.LoggerExtensions.LogDebug.

Rule description

For high-performance logging scenarios, use the LoggerMessage pattern instead of Microsoft.Extensions.Logging.Logger extension methods.

How to fix violations

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

csharp
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.

csharp
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();
}

Microsoft.Extensions.Logging.LoggerMessage provides the following performance advantages over Microsoft.Extensions.Logging.Logger extension methods:

When to suppress warnings

Do not suppress a warning from this rule.

See also