All rules
CA1848Performance Enabled by default: No

Use the LoggerMessage delegates

Use the LoggerMessage delegates

Microsoft docs

Description

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

Cause

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

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

The following code fixes the violation.

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

  • Logger extension methods require "boxing" (converting) value types, such as int, into object. The Microsoft.Extensions.Logging.LoggerMessage pattern avoids boxing by using static System.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. Microsoft.Extensions.Logging.LoggerMessage only requires parsing a template once when the message is defined.

Example

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!");
   }
}

When to suppress

Do not suppress a warning from this rule.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0