All rules
CA1873Performance Enabled by default: As suggestion

Avoid potentially expensive logging

Avoid potentially expensive logging

Microsoft docs

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 Microsoft.Extensions.Logging.ILogger.IsEnabled or use *source-generated logging* with the Microsoft.Extensions.Logging.LoggerMessageAttribute attribute.

Cause

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

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 Microsoft.Extensions.Logging.ILogger.IsEnabled.
  • Use source-generated logging with the Microsoft.Extensions.Logging.LoggerMessageAttribute attribute.
  • Ensure expensive operations aren't performed in logging arguments unless necessary.

Example

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

When to suppress

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.

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