Skip to content

Conversation

@Thomas-Shephard
Copy link

@Thomas-Shephard Thomas-Shephard commented Jan 3, 2026

Summary

Fixes a bug in the CA1873 analyzer where logging calls that were guarded by IsEnabled were being incorrectly flagged when using LoggerMessage.

Problem

The analyzer was not associating the Ilogger instance used in the IsEnabled check with the one used in LoggerMessage causing false positives even when the code was being guarded correctly.

Fixes #50893

Fix

Updated the AreInvocationsOnSameInstance logic to correctly identify whether this is the case.

Testing

Added a new test GuardedLoggerMessage_NoDiagnostic_CS and ensured all existing tests continue to pass

Copilot AI review requested due to automatic review settings January 3, 2026 23:45
@Thomas-Shephard Thomas-Shephard requested a review from a team as a code owner January 3, 2026 23:45
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a false positive in the CA1873 analyzer where logging calls guarded by IsEnabled checks were incorrectly flagged when using LoggerMessage attribute-based logging methods.

Key Changes

  • Updated AreInvocationsOnSameInstance method to recognize when a LoggerMessage method and an IsEnabled check are using the same logger instance
  • Added special handling for both static LoggerMessage methods (with explicit logger parameter) and instance LoggerMessage methods (with captured logger from class members)
  • Added test coverage for guarded LoggerMessage scenarios

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
AvoidPotentiallyExpensiveCallWhenLogging.cs Enhanced logger instance matching logic to support LoggerMessage patterns, including heuristic for instance methods that capture loggers from class fields/properties/constructor parameters
AvoidPotentiallyExpensiveCallWhenLoggingTests.cs Added test case for guarded LoggerMessage calls using both instance and static patterns with primary constructor parameters

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CA1873 False positive for guarded non-extension logger calls in .NET 10

1 participant