Edit

Share via


CA1873: Avoid potentially expensive logging

Property Value
Rule ID CA1873
Title Avoid potentially expensive logging
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 10 As suggestion

Cause

In many situations, logging is disabled or set to a log level that results in an unnecessary evaluation for logging arguments.

Rule description

When logging methods are called, their arguments are evaluated regardless of whether the logging level is enabled. This can result in expensive operations being executed even when the log message won't be written. For better performance, guard expensive logging calls with a check to IsEnabled or use the LoggerMessage pattern.

How to fix violations

To fix a violation of this rule, use one of the following approaches:

  • Guard the logging call with a check to IsEnabled.
  • Use the LoggerMessage pattern with LoggerMessageAttribute.
  • Ensure expensive operations aren't performed in logging arguments unless necessary.

Example

The following code snippet shows violations of CA1873:

using Microsoft.Extensions.Logging;

class Example
{
    private readonly ILogger _logger;

    public Example(ILogger<Example> logger)
    {
        _logger = logger;
    }

    public void ProcessData(int[] data)
    {
        // Violation: expensive operation in logging argument.
        _logger.LogDebug($"Processing {string.Join(", ", data)} items");

        // Violation: object creation in logging argument.
        _logger.LogTrace("Data: {Data}", new { Count = data.Length, Items = data });
    }
}
Imports Microsoft.Extensions.Logging

Class Example
    Private ReadOnly _logger As ILogger

    Public Sub New(logger As ILogger(Of Example))
        _logger = logger
    End Sub

    Public Sub ProcessData(data As Integer())
        ' Violation: expensive operation in logging argument.
        _logger.LogDebug($"Processing {String.Join(", ", data)} items")

        ' Violation: object creation in logging argument.
        _logger.LogTrace("Data: {Data}", New With {.Count = data.Length, .Items = data})
    End Sub
End Class

The following code snippet fixes the violations:

using Microsoft.Extensions.Logging;

class Example
{
    private readonly ILogger _logger;

    public Example(ILogger<Example> logger)
    {
        _logger = logger;
    }

    public void ProcessData(int[] data)
    {
        // Fixed: guard with IsEnabled check.
        if (_logger.IsEnabled(LogLevel.Debug))
        {
            _logger.LogDebug($"Processing {string.Join(", ", data)} items");
        }

        // Fixed: guard with IsEnabled check.
        if (_logger.IsEnabled(LogLevel.Trace))
        {
            _logger.LogTrace("Data: {Data}", new { Count = data.Length, Items = data });
        }
    }
}
Imports Microsoft.Extensions.Logging

Class Example
    Private ReadOnly _logger As ILogger

    Public Sub New(logger As ILogger(Of Example))
        _logger = logger
    End Sub

    Public Sub ProcessData(data As Integer())
        ' Fixed: guard with IsEnabled check.
        If _logger.IsEnabled(LogLevel.Debug) Then
            _logger.LogDebug($"Processing {String.Join(", ", data)} items")
        End If

        ' Fixed: guard with IsEnabled check.
        If _logger.IsEnabled(LogLevel.Trace) Then
            _logger.LogTrace("Data: {Data}", New With {.Count = data.Length, .Items = data})
        End If
    End Sub
End Class

When to suppress warnings

It's safe to suppress a warning from this rule if performance isn't a concern or if the logging arguments don't involve expensive operations.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1873
// The code that's violating the rule is on this line.
#pragma warning restore CA1873

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1873.severity = none

For more information, see How to suppress code analysis warnings.

See also