Logger Constant Template

ID

csharp.logger_constant_template

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

CSharp

Tags

code_smell, logging, performance

Description

Reports logger calls whose first argument is a $"…​" string interpolation. The interpolation builds the message eagerly even when the log level is disabled, which wastes allocations on every disabled call and prevents structured-logging backends from indexing the values.

Rationale

Templated messages (log.Info("user {Id} signed in", id)) are evaluated lazily by modern logging frameworks (Serilog, Microsoft.Extensions.Logging, NLog). When the sink is disabled, the placeholder substitution never runs. When it is enabled, each value is kept as a structured field instead of being concatenated into a single string, which makes the resulting log queryable.

public class Audit
{
    public void Bad(ILogger log, string user, int id)
    {
        log.Info($"user {user} signed in with id {id}");        // FLAW
    }

    public void Good(ILogger log, string user, int id)
    {
        log.Info("user {User} signed in with id {Id}", user, id); // OK
    }
}

Remediation

Replace $"…​" with a literal template and pass the values as positional arguments. Use named placeholders ({User}, {Id}) so that structured-logging sinks expose them as searchable fields.