CA2254: Template should be a static expression

Value
Rule ID CA2254
Category Usage
Fix is breaking or non-breaking Non-breaking

Cause

A message template passed to a logger API is not constant.

Rule description

When performing logging, it's desirable to preserve the structure of the log (including placeholder names) along with the placeholder values. Preserving this information allows for better observability and search in log aggregation and monitoring software.

Preferred:

var firstName = "Lorenz";
var lastName = "Otto";

// This tells the logger that there are FirstName and LastName properties
// on the log message, and correlates them with the argument values.
logger.Warning("Person {FirstName} {LastName} encountered an issue", firstName, lastName);

Not preferred:

// DO NOT DO THIS

var firstName = "Lorenz";
var lastName = "Otto";

// Here, the log template itself is changing, and the association between named placeholders and their values is lost.
logger.Warning("Person " + firstName + " " + lastName + " encountered an issue");

// String interpolation also loses the association between placeholder names and their values.
logger.Warning($"Person {firstName} {lastName} encountered an issue");

The logging message template should not vary between calls.

How to fix violations

Update the message template to be a constant expression. If you're using values directly in the template, refactor them to use named placeholders instead.

logger.Warning("Person {FirstName} {LastName} encountered an issue", firstName, lastName);

When to suppress errors

Do not suppress a warning from this rule.

See also