Updated on

A logging message template is a constant string with named placeholders, such as "User {userName} logged on {loggedInTime}", and the values go in as separate arguments. The logger then keeps each value as a named property. CA2254 is the code analysis warning we get when the template is built with string interpolation or concatenation instead.

We’ll start with how logging got here, from plain text to structured events, because that history explains why the rule exists and how to fix it.

To download the source code for this article, you can visit our GitHub repository.

All the examples live in one console app that runs on the generic host, so the project needs the Microsoft.Extensions.Hosting package. If ILogger itself is new to you, start with our article on ILogger, ILoggerFactory and ILoggerProvider. Our Program.cs registers an Application class and calls its Run() method:

using MessageTemplateForLoggingCA2254;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<Application>();

using var host = builder.Build();

var app = host.Services.GetRequiredService<Application>();

app.Run();

The Application class gets an ILogger<Application> from the container, and Run() calls each logging method from this article in turn:

using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace MessageTemplateForLoggingCA2254;
public class Application
{
    private readonly ILogger<Application> _logger;

    public Application(ILogger<Application> logger)
    {
        _logger = logger;
    }

    public void Run()
    {
        var userName = "John Doe";
        var loggedInTime = DateTime.UtcNow;
        var userId = Guid.NewGuid();
        LogMessageWithJson(userName, loggedInTime);
        LogMessageWithSamePlaceholderAndVariableName(userName);
        LogMessageWithDifferentPlaceholderAndVariableName(userName);
        LogMessageWithoutFormatting(userId, loggedInTime);
        LogMessageWithFormatting(userId, loggedInTime);
        LogMessageWithCA2254Warning(userName, loggedInTime);
        LogMessageToFixCA2254Warning(userName, loggedInTime);
    }
}

Every method we show from here on goes inside this class.

Let’s start.

A Brief History of Structured Logging APIs

Initially, in the early days of application logging, streaming text was the standard approach, effective for simple scenarios. Don’t copy this one into new code, though. It’s the exact call CA2254 warns about:

public void LogMessageWithCA2254Warning(string userName, DateTime loggedInTime)
{
    _logger.Log(LogLevel.Information, $"User {userName} logged on {loggedInTime}");
}

With a result like this one (the time changes on every run):

User John Doe logged on 12/4/2023 11:01:39 PM

However, as the industry evolved to tackle more complex cases, such as distributed systems, parsing these logs became increasingly burdensome. Consequently, this challenge gave rise to the concept of structured logging. The central idea was to treat log data as a stream of structured events with key-value properties. These structured events are far more manageable in large-scale services. Specifically, querying based on properties offers a more efficient and user-friendly experience compared to the regular expressions that were commonly used in the early days of logging. A prime example of this direct encoding of events is the JSON format:

public void LogMessageWithJson(string userName, DateTime loggedInTime)
{
    var logEntry = new
    {
        EventId = "logged_in",
        Username = userName,
        Time = loggedInTime,
    };

    var message = JsonSerializer.Serialize(logEntry);
    _logger.Log(LogLevel.Information, message);
}

This is the output we can find (the time changes on every run):

{"EventId":"logged_in","Username":"John Doe","Time":"2023-12-04T23:01:39.2034813Z"}

Subsequently, while this convention eases log filtering, allowing for queries such as Username = 'John Doe' to be performed directly on the unprocessed log stream, in practice, it introduces another challenge: a long stream of key-value pairs is hard for people to read.

This call raises CA2254 too, because message is a variable that holds a different string for every user.

Furthermore, logging systems like Event Tracing for Windows attempted to address this issue by balancing good performance with human and machine readability. Nevertheless, the effort required for developers to assign event IDs and manage manifests often proved to be more trouble than it was worth.

Semantic or Structured Logging

Moving forward, message templates combine the strengths of various approaches, delivering optimal human readability, impeccable machine interpretability, and exceptional ease of use during development.

A template offers placeholders to be populated with event data. Inside a method that receives userName and loggedInTime, the call looks like this:

_logger.Log(LogLevel.Information, "User {userName} logged on {loggedInTime}", userName, loggedInTime);

In this context, we are treating the sentence above as an event type, with the variables filling the gaps being the only changing elements. This approach allows sentences to be grouped by these gaps, thereby offering enhanced flexibility in data retrieval.

Serilog is built around the same idea, and our guide to structured logging with Serilog shows it with a real log sink.

How Do Placeholders in a Log Message Template Work?

A log message template is a constant string with placeholders in curly braces, followed by one argument for each placeholder.

The logger matches arguments to placeholders by position, not by name. Microsoft Learn says it directly: “The order of placeholders, not their names, determines which parameters are used to provide their values.” The first argument fills the first placeholder, whatever the variable is called.

The names still matter, though. Each placeholder name becomes the name of a property on the log entry, stored next to the value it received. A log store can then filter on userName without parsing any text.

That’s why we use names for placeholders and not numbers. A template like "User {0} logged on" still logs the right text, but the value ends up in a property called 0, and nobody is going to search for that.

Here is a template with one placeholder and its matching argument:

public void LogMessageWithSamePlaceholderAndVariableName(string userName)
{
    _logger.Log(LogLevel.Information, "User '{userName}' added apples to the basket.", userName);
}

The userName variable corresponds to the placeholder {userName}. Again, what matters with variables and placeholders is their order, not their names. For example, the following code would also work successfully:

public void LogMessageWithDifferentPlaceholderAndVariableName(string randomSentence)
{
    _logger.Log(LogLevel.Information, "User '{userName}' added apples to the basket.", randomSentence);
}

Both examples produce the same output:

User 'John Doe' added apples to the basket.

Formatting Log Message Templates in C#

Moreover, in C#, log message template placeholders support formatting, enabling us to specify any valid format for a given type of argument. This enhances the readability and usefulness of our log messages, which is particularly valuable when logging unique identifiers or timestamps.

Let’s consider a scenario where we need to log a user’s action along with the timestamp. A standard log entry might look like this:

public void LogMessageWithoutFormatting(Guid userId, DateTime loggedInTime)
{
    _logger.Log(LogLevel.Information, "User {userId} logged in at {loggedInTime}.", userId, loggedInTime);
}

Example output:

User 5bc96623-0a1b-4ee0-983e-fe0335a418c4 logged in at 01/15/2024 21:00:11.

In the previous example, userId is a GUID and loggedInTime is a DateTime object. While this provides the necessary information, we can enhance the log’s readability by applying formatting to these values:

public void LogMessageWithFormatting(Guid userId, DateTime loggedInTime)
{
    _logger.Log(LogLevel.Information, "User {userId:N} logged in at {loggedInTime:F}.", userId, loggedInTime);
}

In this revised example, {userId:N} applies a format specifier to the GUID, removing the dashes and shortening the overall string length. The {loggedInTime:F} specifier applies a full date/time pattern (long date and long time) to the DateTime object, resulting in a comprehensive and readable timestamp.

Which results in a log message similar to:

User 5bc966230a1b4ee0983efe0335a418c4 logged in at Monday, 15 January 2024 21:00:11.

With these format specifiers, the log entry becomes both compact and rich with detailed information. The 'N' format for GUIDs provides a cleaner, uninterrupted string, while the 'F' format for the DateTime yields a full, unambiguous timestamp. These enhancements aid significantly in log readability and analysis.

What Does an Interpolated Log Message Lose?

On the console, the interpolated call and the template call print almost the same line. To see the difference, we have to look at what a log store receives. The console logger has a JSON formatter for that, and because Host.CreateApplicationBuilder(args) reads command-line arguments as configuration, we can switch to it without touching the code:

dotnet run -- --Logging:Console:FormatterName=json --Logging:Console:FormatterOptions:JsonWriterOptions:Indented=true

Here are the entries from LogMessageWithCA2254Warning() and LogMessageToFixCA2254Warning(), with the times of our run:

{
  "EventId": 0,
  "LogLevel": "Information",
  "Category": "MessageTemplateForLoggingCA2254.Application",
  "Message": "User John Doe logged on 11/14/2026 1:16:43 PM",
  "State": {
    "{OriginalFormat}": "User John Doe logged on 11/14/2026 1:16:43 PM"
  }
}
{
  "EventId": 0,
  "LogLevel": "Information",
  "Category": "MessageTemplateForLoggingCA2254.Application",
  "Message": "User John Doe logged on 11/14/2026 13:16:43",
  "State": {
    "userName": "John Doe",
    "loggedInTime": "11/14/2026 13:16:43",
    "{OriginalFormat}": "User {userName} logged on {loggedInTime}"
  }
}

The interpolated entry has a single property, {OriginalFormat}, and its value is the finished sentence. Every login produces a new “template”, so a log store can’t group these entries or filter them by user. The template entry keeps userName and loggedInTime as separate properties, next to a template that is the same on every call.

The two times don’t match either. The first one ends in “PM” because string interpolation formats values with the current culture, which was en-US in our run. The logger formats template arguments with the invariant culture, so the second line reads the same on any machine.

The same goes for format specifiers. In the {userId:N} entry from the formatting section, the message drops the GUID’s dashes, while the userId property still holds the full GUID.

There’s a cost side too. An interpolated string is built before the logger gets a chance to check the log level. If Information is turned off, the template call skips the formatting, but the interpolated string has already been created.

What Does CA2254 Mean?

CA2254 is the .NET code analysis rule titled “Template should be a static expression”. Its message is the sentence most of us end up searching for. Microsoft Learn puts it as: “The logging message template should not vary between calls.”

The rule fires when the string we pass as the message template is built at run time, with string interpolation or concatenation. LogMessageWithCA2254Warning() does exactly that, and so does LogMessageWithJson(), whose template is a variable.

The warning is also easy to miss. CA2254 is one of the Roslyn analyzers that ship with the SDK, and Learn lists it as enabled by default “As suggestion”. The IDE marks the line with a hint, but dotnet build prints nothing, and neither does CI.

To make the build report it, we raise its severity in an .editorconfig file next to the solution:

root = true

[*.cs]
dotnet_diagnostic.CA2254.severity = warning

Now the build lists both methods (the line numbers are from the sample’s Application.cs):

Application.cs(38,43): warning CA2254: The logging message template should not vary between calls to 'LoggerExtensions.Log(ILogger, LogLevel, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2254)
Application.cs(63,43): warning CA2254: The logging message template should not vary between calls to 'LoggerExtensions.Log(ILogger, LogLevel, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2254)

How Do We Fix CA2254?

To resolve this warning, it’s important to follow the recommended practice of maintaining the structure of the log, including the names of placeholders. This improves observability for aggregation and monitoring tools like Grafana, Application Insights, and others:

public void LogMessageToFixCA2254Warning(string userName, DateTime loggedInTime)
{
    _logger.Log(LogLevel.Information, "User {userName} logged on {loggedInTime}", userName, loggedInTime);
}

By indicating to the logger that the userName and loggedInTime properties in the message correspond with the placeholder values, the updated message template becomes a constant expression, effectively fixing the warning.

The JSON method gets the same fix. We pass the fields as arguments to a constant template and let the log provider write them out, as the JSON console formatter did in the previous section.

Learn says it’s safe to suppress CA2254 when we don’t need structured logging, or when the template comes from a resource file. On a hot path, the next step after a constant template is the compile-time logging source generator, where a [LoggerMessage] attribute turns each template into a strongly typed method.

Conclusion

We’ve seen how logging moved from plain text to structured events, and how a message template keeps the values of a log entry as named properties. Placeholders take their arguments by position, and their names become the property names a log store can search.

String interpolation throws that structure away. It also formats with the current culture and runs even when the log level is off. That’s what CA2254 warns us about, and since it ships as a suggestion, adding one line to .editorconfig is the easiest way to make the build tell us.

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and Microsoft.Extensions.Hosting 11.0.0.