Skip to content

Provide a Code Fix for CA1873 to Automatically Generate LoggerMessageAttribute Methods #129566

@Varorbc

Description

@Varorbc

Problem Description

The .NET code analysis rule CA1873: Avoid possible expensive logging correctly identifies performance‑sensitive logging patterns. However, the analyzer currently does not provide a corresponding Code Fix to help developers automatically migrate these logging calls to the recommended LoggerMessageAttribute or LoggerMessage.Define pattern.

For projects with a large number of ILogger.LogXXX calls, manually converting each log statement is time‑consuming and error‑prone.


Requested Feature

Please consider adding an automatic Code Fix Provider for CA1873 that can transform a standard logging call into a generated LoggerMessageAttribute method.

Example

Original code
_logger.LogInformation("User {UserId} logged in", userId);
Expected auto‑fix
[LoggerMessage(EventId = 0, Level = LogLevel.Information, Message = "User {UserId} logged in")]
static partial void UserLoggedIn(ILogger logger, string userId);

UserLoggedIn(_logger, userId);

Why this feature is important

  • CA1873 encourages using source‑generated logging for better performance, but the migration path is currently manual.
  • Large codebases may contain hundreds or thousands of logging statements, making manual conversion impractical.
  • A built‑in Code Fix would significantly improve developer productivity and accelerate adoption of high‑performance logging patterns.

Additional Suggestions (optional)

  • Auto‑generated EventId could default to 0 or prompt the user to adjust it.
  • Support applying the fix to an entire document or project.
  • Optionally detect and consolidate repeated log messages into a single generated method.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-Loggingcode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixer

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions