CA2254:模板应为静态表达式

属性
规则 ID CA2254
标题 模板应为静态表达式
类别 使用情况
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用 作为建议

原因

传递给记录器 API 的消息模板不是常量。 当传递的模板使用字符串串联或内插时,将发生这种情况。 模板应是一个常量值,该值表示消息模板格式的日志消息。 例如: "User {User} logged in from {Address}"。 有关详细信息,请参阅日志消息模板格式设置

规则说明

执行日志记录操作时,最好保留日志的结构(包括占位符名称)以及占位符值。 保留此信息可以在日志聚合和监视软件中改进可观测性和搜索性。

首选:

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);

非首选:

// 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");

日志记录消息模板不应因调用而异。

如何解决冲突

将消息模板更新为常量表达式。 如果直接在模板中使用值,请重构模板以改用命名占位符。

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

何时禁止显示错误

如果用例不需要结构化日志记录,则可以安全地禁止显示来自此规则的警告。 如果日志消息模板在资源文件中定义,则禁止显示此规则也是安全的。

另请参阅