S6672 — Generic logger injection should match enclosing type

Language
C#
Type
Code smell
Severity
Minor
Tags
confusing, logging

Why is this an issue?

In most logging frameworks, it’s good practice to set the logger name to match its enclosing type, as enforced by {rule:csharpsquid:S3416}.

Logging frameworks can define or use Generic interfaces for the logger, such as ILogger<TCategoryName>.

The use of a logger of a generic type parameter A (e.g. ILogger<A>) in a type different than A, say B, goes against the convention.

Because the instance of type A would log with a logger named after B, log items would appear as if they were logged by B instead, resulting in confusion and logging misconfiguration:

Further details and examples are provided in {rule:csharpsquid:S3416}.

This rule specifically targets the generic logging interface ILogger<TCategoryName> Interface defined by Microsoft Extensions Logging.

How to fix it

Change the generic type parameter of the ILogger interface to match the enclosing type.

Noncompliant code example


class EnclosingType
{
    public EnclosingType(ILogger<AnotherType> logger) // Noncompliant
    {
        // ...
    }
}

Compliant solution


class EnclosingType
{
    public EnclosingType(ILogger<EnclosingType> logger) // Compliant
    {
        // ...
    }
}

Resources

Documentation

↑ Back to top