How to reuse a structured log message without violating CA2254 in .NET
You want the same message in ILogger and in an event bus payload, but interpolating it once trips CA2254 and kills structured logging. Tested on .NET 11.0.0: which template expressions CA2254 accepts, what each workaround puts in the log state, and a small MessageTemplate type that logs as structured state and renders byte-identical text for the payload.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
Define the message once as a const string message template, not as an interpolated string. Pass that constant plus the values to the logger (LogWarning(Templates.PersonIssue, firstName, lastName) or a [LoggerMessage] method with Message = Templates.PersonIssue), and render the same template a second time for the external payload. CA2254 only asks that the template be a compile-time constant: on .NET 11.0.0 with SDK 11.0.100 it accepts a const field, a const interpolated string and constant concatenation, and it flags static readonly fields, properties, locals and parameters. If you want one object that serves both sides, wrap the template and the values in a small state type that implements IReadOnlyList<KeyValuePair<string, object?>>, log it with ILogger.Log<TState>, and call ToString() on it for the bus. The full type is below, and on the 12 edge cases tested here it renders exactly the text Microsoft.Extensions.Logging produces.
This post answers an unanswered Stack Overflow question asked against the CA2254 docs example. Everything below was compiled and run with SDK 11.0.100 on runtime 11.0.0 (macOS arm64), Microsoft.Extensions.Logging.Console 11.0.0, Serilog.Extensions.Logging 11.0.0, Serilog.Sinks.Console 6.1.1 and Serilog.Formatting.Compact 3.0.0.
The code that trips CA2254
The question starts from the “don’t do this” example on the CA2254 docs page and adds a second consumer:
// .NET 11.0.0, C# 15
var firstName = "Lorenz";
var lastName = "Otto";
var errorMessage = $"Person {firstName} {lastName} encountered an issue";
logger.LogWarning(errorMessage); // CA2254
eventBus.Publish(new Payload(errorMessage)); // needs the same text
The intent is reasonable: one sentence, written once, used twice. The problem is that the logger is the only one of the two consumers that cares about structure, and the interpolated string has already thrown the structure away before LogWarning runs.
CA2254 is “Enabled by default in .NET 11: As suggestion”, so a plain dotnet build prints nothing. You only see it in the IDE, or after raising it in .editorconfig:
# .editorconfig -- .NET 11 SDK analyzers
[*.cs]
dotnet_diagnostic.CA2254.severity = warning
With that in place, the build reports:
warning CA2254: The logging message template should not vary between calls to
'LoggerExtensions.LogWarning(ILogger, string?, params object?[])'
What the rule actually accepts
The docs say the template “should be a constant value”. Constant here means a C# constant expression, not “a value that happens to never change”. To pin that down, this file was built with CA2254 at warning severity against Microsoft.Extensions.Logging.Abstractions 11.0.0:
// .NET 11.0.0, SDK 11.0.100, C# 15, AnalysisLevel latest
using Microsoft.Extensions.Logging;
public partial class Cases(ILogger logger)
{
const string ConstTemplate = "Person {FirstName} {LastName} encountered an issue";
static readonly string ReadonlyTemplate = "Person {FirstName} {LastName} encountered an issue";
const string Prefix = "Person";
const string ConstInterpolated = $"{Prefix} {{FirstName}} {{LastName}} encountered an issue";
static string PropertyTemplate => "Person {FirstName} {LastName} encountered an issue";
public void Run(string firstName, string lastName, string template)
{
logger.LogWarning("Person {FirstName} {LastName} encountered an issue", firstName, lastName);
logger.LogWarning($"Person {firstName} {lastName} encountered an issue");
var errorMessage = $"Person {firstName} {lastName} encountered an issue";
logger.LogWarning(errorMessage);
logger.LogWarning(ConstTemplate, firstName, lastName);
logger.LogWarning(ReadonlyTemplate, firstName, lastName);
logger.LogWarning(ConstInterpolated, firstName, lastName);
logger.LogWarning(PropertyTemplate, firstName, lastName);
logger.LogWarning(template, firstName, lastName);
logger.LogWarning("Person " + "{FirstName} {LastName} encountered an issue", firstName, lastName);
var d = LoggerMessage.Define<string, string>(LogLevel.Warning, default, template);
logger.Log(LogLevel.Warning, default, "x", null, (s, e) => s);
logger.LogWarning(Messages.Shared, firstName, lastName);
}
[LoggerMessage(Level = LogLevel.Warning, Message = ConstTemplate)]
public partial void LogIssue(string firstName, string lastName);
}
public static class Messages
{
public const string Shared = "Person {FirstName} {LastName} encountered an issue";
}
| Template expression | CA2254 on SDK 11.0.100 |
|---|---|
| String literal | clean |
$"..." with runtime values | warning |
Local string holding an interpolated value | warning |
const string field (same class or another class) | clean |
const interpolated string built from other constants | clean |
Constant concatenation "a" + "b" | clean |
static readonly string field | warning |
| Expression-bodied property returning a literal | warning |
| Method parameter | warning |
LoggerMessage.Define with a parameter as the format | clean (not analyzed) |
ILogger.Log<TState> with a custom state | clean (no template argument) |
[LoggerMessage(Message = ConstTemplate)] | clean (attribute arguments must be constant anyway) |
Two rows matter for the reuse problem. First, static readonly is rejected even though it never changes at runtime, so if you are moving the template into a shared class, make it const. Second, the rule only inspects the template argument of the logger extension methods. It cannot see what you do with the values, and it has nothing to say about ILogger.Log<TState>, which is exactly what the structured option below relies on.
What each workaround puts in the log
Whether a workaround is “good” depends on what reaches the provider, not on whether the warning goes away. Here are five variants of the same message, run through the JSON console formatter (AddJsonConsole) on .NET 11.0.0:
// .NET 11.0.0, Microsoft.Extensions.Logging.Console 11.0.0
// 1. The question's code, with CA2254 suppressed
var errorMessage = $"Person {firstName} {lastName} encountered an issue";
#pragma warning disable CA2254
logger.LogWarning(errorMessage);
#pragma warning restore CA2254
// 2. The sentence inside a single placeholder
logger.LogWarning("{ErrorMessage}", errorMessage);
// 3. A const template
logger.LogWarning(Templates.PersonIssue, firstName, lastName);
// 4. The same const through the [LoggerMessage] source generator
Log.PersonIssue(logger, firstName, lastName);
// 5. One LogMessage object (the type is defined further down)
LogMessage msg = Templates.PersonIssueTemplate.With(firstName, lastName);
logger.Log(LogLevel.Warning, msg);
The State property of each line, as printed:
{"{OriginalFormat}":"Person Lorenz Otto encountered an issue"}
{"ErrorMessage":"Person Lorenz Otto encountered an issue","{OriginalFormat}":"{ErrorMessage}"}
{"FirstName":"Lorenz","LastName":"Otto","{OriginalFormat}":"Person {FirstName} {LastName} encountered an issue"}
{"FirstName":"Lorenz","LastName":"Otto","{OriginalFormat}":"Person {FirstName} {LastName} encountered an issue"}
{"FirstName":"Lorenz","LastName":"Otto","{OriginalFormat}":"Person {FirstName} {LastName} encountered an issue"}
The Message field is Person Lorenz Otto encountered an issue on all five, which is why option 1 looks fine in a console and only hurts later. Routing the same calls through Serilog’s CompactJsonFormatter shows the effect on the template (@mt) that log backends group by:
{"@mt":"Person Lorenz Otto encountered an issue","@l":"Warning","SourceContext":"Demo"}
{"@mt":"{ErrorMessage}","@l":"Warning","ErrorMessage":"Person Lorenz Otto encountered an issue","SourceContext":"Demo"}
{"@mt":"Person {FirstName} {LastName} encountered an issue","@l":"Warning","FirstName":"Lorenz","LastName":"Otto","SourceContext":"Demo"}
{"@mt":"Person {FirstName} {LastName} encountered an issue","@l":"Warning","FirstName":"Lorenz","LastName":"Otto","EventId":{"Id":1001,"Name":"PersonIssue"},"SourceContext":"Demo"}
{"@mt":"Person {FirstName} {LastName} encountered an issue","@l":"Warning","FirstName":"Lorenz","LastName":"Otto","SourceContext":"Demo"}
(Timestamps trimmed.) Reading the two outputs together:
- Option 1 turns every distinct person into a distinct template. You cannot query
LastName = "Otto", and “how often did this warning fire” becomes a fuzzy text search. - Option 2 silences CA2254 and is a common suggestion, but it is the same data loss with extra steps. Every message in the codebase shares the template
{ErrorMessage}, so grouping by template is now useless in the other direction. Use it only when the text genuinely comes from somewhere you do not control, such as an exception message from a third-party API. - Options 3, 4 and 5 produce identical structured state. The difference is only in how you get the payload text.
Fix 1: a const template, rendered twice
If the logging side is all you care about structurally, the smallest change is to make the template the shared thing instead of the sentence:
// .NET 11.0.0, C# 15
static class Templates
{
public const string PersonIssue = "Person {FirstName} {LastName} encountered an issue";
}
static partial class Log
{
[LoggerMessage(EventId = 1001, Level = LogLevel.Warning, Message = Templates.PersonIssue)]
public static partial void PersonIssue(ILogger logger, string firstName, string lastName);
}
The [LoggerMessage] attribute takes the constant directly, so the source generator, CA2254 and CA1848 are all satisfied, and you get the generator’s IsEnabled check for free (see the CA1873 post for why that check matters). If you are not using the generator yet, logger.LogWarning(Templates.PersonIssue, firstName, lastName) is equally clean.
That leaves the payload. The template is not a string.Format string, so string.Format(Templates.PersonIssue, ...) throws FormatException, and hand-writing $"Person {firstName} {lastName}..." for the bus brings back the duplication the question was trying to avoid. You need something that renders a named-hole template the way the logger does. That is the MessageTemplate type in the next section; with it the bus side becomes:
// .NET 11.0.0
Log.PersonIssue(logger, firstName, lastName);
eventBus.Publish(new Payload(Templates.PersonIssueTemplate.With(firstName, lastName).ToString()));
The cost of this shape is that the arguments are passed twice, once to the log method and once to With. The compiler checks the log method’s parameter count; With checks it at runtime.
Fix 2: one object that is both the log state and the payload
ILogger has exactly one real logging method, Log<TState>(LogLevel, EventId, TState, Exception?, Func<TState, Exception?, string>). Every LogWarning overload builds an internal FormattedLogValues struct and calls it. Providers do not look for FormattedLogValues specifically: they treat any TState that implements IReadOnlyList<KeyValuePair<string, object?>> as named properties and use the {OriginalFormat} entry as the template. The console JSON formatter and Serilog’s provider are checked in the output above; OpenTelemetry’s logger provider reads the same interface for its log attributes (not run for this post). The [LoggerMessage] generator relies on the same contract: for a method with seven parameters it emits a private readonly struct implementing that interface instead of calling LoggerMessage.Define.
So you can build your own state type that holds the template and the values, log it, and ToString() it for the bus:
// .NET 11.0.0, C# 15, Microsoft.Extensions.Logging.Abstractions 11.0.0
using System.Collections;
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Logging;
/// <summary>A parsed message template: define it once, render it anywhere.</summary>
public sealed class MessageTemplate
{
private readonly CompositeFormat _format;
private readonly string[] _names;
public MessageTemplate(string template)
{
Template = template;
var names = new List<string>();
var sb = new StringBuilder();
for (int i = 0; i < template.Length; i++)
{
char c = template[i];
if ((c == '{' || c == '}') && i + 1 < template.Length && template[i + 1] == c)
{
sb.Append(c).Append(c); // escaped {{ or }}
i++;
continue;
}
if (c != '{') { sb.Append(c); continue; }
int close = template.IndexOf('}', i);
if (close < 0) throw new FormatException($"Unclosed hole in '{template}'.");
string hole = template[(i + 1)..close]; // Name[,alignment][:format]
int cut = hole.IndexOfAny([',', ':']);
names.Add(cut < 0 ? hole : hole[..cut]);
sb.Append('{').Append(names.Count - 1).Append(cut < 0 ? "" : hole[cut..]).Append('}');
i = close;
}
_names = [.. names];
_format = CompositeFormat.Parse(sb.ToString());
}
public string Template { get; }
public IReadOnlyList<string> Names => _names;
public LogMessage With(params object?[] values)
{
if (values.Length != _names.Length)
throw new ArgumentException($"Template '{Template}' has {_names.Length} holes, got {values.Length} values.");
return new LogMessage(this, values);
}
internal string Render(object?[] values)
{
var formatted = new object?[values.Length];
for (int i = 0; i < values.Length; i++)
formatted[i] = FormatArgument(values[i]);
return string.Format(CultureInfo.InvariantCulture, _format, formatted);
}
// Same rules as Microsoft.Extensions.Logging's LogValuesFormatter:
// null -> "(null)", non-string IEnumerable -> comma separated, invariant culture.
private static object FormatArgument(object? value) => value switch
{
null => "(null)",
string s => s,
IEnumerable e => string.Join(", ", e.Cast<object?>().Select(x =>
x is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture) : x?.ToString() ?? "(null)")),
_ => value,
};
}
/// <summary>One rendered occurrence. Also a valid ILogger state object.</summary>
public sealed class LogMessage(MessageTemplate template, object?[] values)
: IReadOnlyList<KeyValuePair<string, object?>>
{
private string? _text;
public MessageTemplate Template => template;
public KeyValuePair<string, object?> this[int index] =>
index < values.Length
? new(template.Names[index], values[index])
: index == values.Length
? new("{OriginalFormat}", template.Template)
: throw new IndexOutOfRangeException();
public int Count => values.Length + 1;
public IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
{
for (int i = 0; i < Count; i++) yield return this[i];
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public override string ToString() => _text ??= template.Render(values);
public static readonly Func<LogMessage, Exception?, string> Formatter = static (m, _) => m.ToString();
}
public static class LogMessageLoggerExtensions
{
public static void Log(this ILogger logger, LogLevel level, LogMessage message,
Exception? exception = null, EventId eventId = default)
{
if (logger.IsEnabled(level))
logger.Log(level, eventId, message, exception, LogMessage.Formatter);
}
}
The call site now has a single definition of the message and a single list of values:
// .NET 11.0.0, C# 15
static class Templates
{
public const string PersonIssue = "Person {FirstName} {LastName} encountered an issue";
public static readonly MessageTemplate PersonIssueTemplate = new(PersonIssue);
}
LogMessage msg = Templates.PersonIssueTemplate.With(firstName, lastName);
logger.Log(LogLevel.Warning, msg);
eventBus.Publish(new Payload(msg.ToString()));
Option 5 in the outputs above is this code. The log state is indistinguishable from LogWarning with a constant template, and the bus receives Person Lorenz Otto encountered an issue. Because LogMessage is an enumerable of name/value pairs, the payload does not have to be a flat string either:
// .NET 11.0.0
var payload = new
{
Text = msg.ToString(),
Template = msg.Template.Template,
Properties = msg.Where(p => p.Key != "{OriginalFormat}").ToDictionary(),
};
// {"Text":"Person Lorenz Otto encountered an issue",
// "Template":"Person {FirstName} {LastName} encountered an issue",
// "Properties":{"FirstName":"Lorenz","LastName":"Otto"}}
That is often what the downstream service wanted in the first place.
Proving the rendered text matches the logger
A second renderer is only useful if it agrees with the first. MessageTemplate mirrors the rules in LogValuesFormatter at the v11.0.0 tag: a hole’s name ends at the first , or :, the rest is passed to string.Format as alignment and format, null becomes (null), any non-string IEnumerable is joined with ", ", and formatting uses CultureInfo.InvariantCulture. To check it, each case below was logged through the real LogWarning into a capturing ILogger that stores formatter(state, exception), and compared with MessageTemplate.With(...).ToString(), with CultureInfo.CurrentCulture set to de-DE:
same | Person Lorenz Otto encountered an issue
same | Total 1,234.50 due 2026-12-03
same | Ratio 0.25 and 3.142
same | Missing (null)
same | Ids 1, 2, 3
same | Prices 1.5, 2.25
same | Literal {braces} around x
same | Value with braces {not a hole}
same | Padded [ ab] [cd ]
same | Destructure { Name = Lorenz } and stringify { Name = Otto }
same | Same name twice 1 2
same | Bool True char z guid 00000000-0000-0000-0000-000000000000
12/12 identical (CurrentCulture = de-DE)
Two details in that output are worth knowing whichever fix you pick:
- The rendered text is always invariant culture.
{Amount:N2}printed1,234.50even though the thread culture was German. If the bus payload is shown to end users, that is probably not what you want, and you should localize from the structured properties on the receiving side rather than from the rendered sentence. @and$are not stripped byMicrosoft.Extensions.Logging. The property name for{@Person}is@Person, and the rendered text is the object’sToString(). Serilog’s provider parses{OriginalFormat}with its own template parser, which is where those prefixes mean destructuring; the built-in providers treat them as part of the name.
Gotchas
const versus static readonly. The PersonIssueTemplate instance is static readonly because it is an object, and that is fine because CA2254 never sees it. The string it is built from should be const so that the [LoggerMessage] attribute and plain LogWarning calls can use the same constant. If you only keep the static readonly string, you lose both.
The analyzer cannot police your wrapper. new MessageTemplate($"Person {firstName} ...") compiles without a warning and reintroduces the exact problem CA2254 exists for. Create templates once, in static readonly fields, from const strings, and treat new MessageTemplate( anywhere else as a code review finding. If you want it enforced, that takes a custom analyzer; nothing in the SDK covers it.
Holes are positional. As with LogWarning, the values are matched to holes by position, not by name. With(lastName, firstName) produces FirstName = "Otto" with no error. The template migration guide covers this trap for ordinary log calls, and it applies unchanged here.
Sensitive data goes to two places now. Whatever you put in the template is logged and published. If either side needs redaction, the [LogProperties] and redaction support only covers the logging path; the payload needs its own filtering.
Option 1’s real cost is downstream. With no arguments, LogWarning(errorMessage) does not even parse the string (FormattedLogValues skips the formatter when values is empty), so it is cheap and cannot throw on braces. The damage is in the backend: one template per distinct sentence in Seq, Loki or any OpenTelemetry store, and no queryable properties.
When suppressing CA2254 is the right call
The docs list two cases: you do not need structured logging, or the template comes from a resource file. A third is text you did not write, such as an upstream service’s error message, where option 2 ("{ErrorMessage}") is honest about what you have. For a message your own code composes from known values, none of those apply, and one of the two fixes above costs a few lines.
Related
- Migrate from ILogger string interpolation to message templates in .NET 11
- Fix CA1873: evaluation of this argument may be expensive
- Structured logging with Serilog and Seq in .NET 11
- Redact sensitive values from logs with [LogProperties]
- What a source generator is and when you need one
Sources
- CA2254: Template should be a static expression, Microsoft Learn
- Log message template formatting, Microsoft Learn
- Compile-time logging source generation, Microsoft Learn
LogValuesFormatter.csandFormattedLogValues.cs, dotnet/runtime atv11.0.0- How can I reuse a structured logging message without violating CA2254?, Stack Overflow
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.