CA2254: Template should be a static expression
Property | Value |
---|---|
Rule ID | CA2254 |
Title | Template should be a static expression |
Category | Usage |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | As suggestion |
Cause
A message template passed to a logger API is not constant. This occurs when the template passed uses either string concatenation or interpolation. Instead, the template should be a constant value that represents the log message in message template format. For example: "User {User} logged in from {Address}"
. For more information, see Log message template formatting.
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 the template to use named placeholders instead.
logger.Warning("Person {FirstName} {LastName} encountered an issue", firstName, lastName);
For usage examples, see the LoggerExtensions.LogInformation method.
When to suppress errors
It's safe to suppress a warning from this rule if your use case doesn't require structured logging. It's also safe to suppress this rule if your log message template is defined in a resource file.