diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1848.md b/docs/fundamentals/code-analysis/quality-rules/ca1848.md index 8660f6af09574..c7f87e009cf19 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1848.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1848.md @@ -1,7 +1,7 @@ --- title: "CA1848: Use the LoggerMessage delegates (code analysis)" description: "Learn about code analysis rule CA1848: Use the LoggerMessage delegates" -ms.date: 01/19/2022 +ms.date: 08/04/2025 f1_keywords: - "LoggerMessageDefineAnalyzer" - "CA1848" @@ -26,13 +26,51 @@ Use of [logger extension methods](xref:Microsoft.Extensions.Logging.LoggerExtens ## Rule description -For high-performance logging scenarios, use the pattern. +For high-performance logging scenarios, use the [LoggerMessage](../../../core/extensions/logger-message-generator.md) pattern instead of extension methods. ## How to fix violations -Use `LoggerMessage` to fix violations of this rule. +Use to fix violations of this rule. (Or, if you're using .NET 5 or earlier, use the class.) - provides the following performance advantages over Logger extension methods: +```csharp +public class SomethingDoer +{ + private readonly ILogger _logger; + public SomethingDoer(ILogger 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 logger) + { + _logger = logger; + } + + public void DoSomething() + { + Log_DidSomething(); + } + + [LoggerMessage(Level = LogLevel.Information, Message = "Did something!")] + private partial void Log_DidSomething(); +} +``` + + provides the following performance advantages over extension methods: - Logger extension methods require "boxing" (converting) value types, such as `int`, into `object`. The pattern avoids boxing by using static 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. only requires parsing a template once when the message is defined. @@ -43,5 +81,6 @@ Do not suppress a warning from this rule. ## See also -- [High-performance logging with LoggerMessage in ASP.NET Core](/aspnet/core/fundamentals/logging/loggermessage) +- [Compile-time logging source generation](../../../core/extensions/logger-message-generator.md) +- [High-performance logging in .NET](../../../core/extensions/high-performance-logging.md) - [Performance rules](performance-warnings.md)