الانتقال إلى المحتوى
.NETASP.NET Core· 6 دقائق للقراءة

Why ILogger Wants Message Templates, Not String Interpolation

The console line looks the same either way, but an interpolated string reaches the logger as finished text with no fields. What templates keep, what interpolation costs when the level is off, and what the source generator adds.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

During an incident, the on-call engineer opens the log search and filters on OrderId = 81723. Nothing comes back, even though the payment service logs every step. A full-text search finds the line: "Payment declined for order 81723: card_declined". The code that wrote it used $"...", so the log store received a finished sentence and no OrderId field. The dashboard meant to count declines by reason has the same problem: there's no Reason field to group on, and every message text is unique.

The common misconception

The belief: passing an interpolated string to ILogger is the same as using a template with placeholders, just more readable. Both produce the same message, and interpolation is checked by the compiler.

The belief is understandable. In the console, the two calls really do print identical lines. String interpolation is the modern C# idiom, and IDEs offer to convert string.Format calls into it. The template syntax, with braces and arguments after it, looks like string.Format with names, a style many developers have been taught to replace.

But a log entry isn't only a line of text. With a template, the logger receives the text's structure; with interpolation, the structure is gone before the logger is called.

What actually happens

A template travels as a constant plus named values

LogWarning("Payment declined for order {OrderId}: {Reason}", orderId, reason) passes the and the values separately. The logger keeps them as key-value pairs: OrderId = 81723, Reason = card_declined, plus the template itself under {OriginalFormat}. Text is produced only when a provider asks for it. A provider, such as OpenTelemetry or Application Insights, can store each value as a field. With the JSON console formatter, a test on .NET 10 printed this (trimmed to the relevant part):

JSON
{  "Message": "Payment declined for order 81723: card_declined",  "State": {    "OrderId": 81723,    "Reason": "card_declined",    "{OriginalFormat}": "Payment declined for order {OrderId}: {Reason}"  }}

Interpolation formats before the logger sees anything

The compiler turns $"Payment declined for order {orderId}: {reason}" into a finished string before LogWarning runs. The logger receives a "template" with no placeholders and no values. In the same test, its state held a single entry: {OriginalFormat}, containing the full sentence. There's nothing to filter on, and because the template differs for every order, nothing to group by either. That's exactly what CA2254 flags: the association between placeholder names and their values is lost.

Values match placeholders by position, not name

With the Log{Level} methods, the names in the template don't bind to your variables; the argument order does. Write "... {OrderId}: {Reason}", reason, orderId and the test logged OrderId = card_declined with no warning. The docs spell it out: placeholders are ordinal-based. The source generator is different: it matches placeholders to parameter names, case-insensitively, and a template placeholder with no matching parameter is a build error (SYSLIB1014).

The cost when the level is off

Interpolation builds its string on every call, before the logger can check whether the level is enabled. In a test with Debug disabled, LogDebug($"... {cart}") called the cart's ToString every time. The template version never formatted anything, but still allocated 64 bytes per call for the argument array and the boxed int. A [LoggerMessage] method allocated nothing: the generated code checks IsEnabled first and takes strongly typed parameters, so value types aren't boxed.

The payment log, fixed

Both versions log a decline at Warning and the cart at Debug:

C# PaymentService.cs
public sealed class PaymentService(ILogger<PaymentService> logger){    public void OnDeclined(int orderId, string reason, Cart cart)    {        // Built before the call: no OrderId field, a new text per order        logger.LogWarning($"Payment declined for order {orderId}: {reason}");        // Calls cart.ToString() even when Debug is off        logger.LogDebug($"Cart at decline: {cart}");    }}

Since .NET 9, an instance [LoggerMessage] method can take its logger from a primary constructor parameter, which is what the right version relies on. A plain template, logger.LogWarning("Payment declined for order {OrderId}: {Reason}", orderId, reason), already fixes the missing fields; the generator adds the zero-allocation path and the compile-time checks.

Three ways to write the same line

$"... {orderId}""... {OrderId}", orderId[LoggerMessage]
Fields in the entryNone, only textOrderId, ReasonOrderId, Reason
{OriginalFormat}The finished sentence, new per orderThe template, same every timeThe template, same every time
Work when the level is offBuilds the string, calls every ToStringAllocates the argument array, boxes value typesNone: checks IsEnabled first
How values meet placeholdersNot at allBy positionBy name, checked at compile time

How to apply it in your project

  1. Find the interpolated callsRaise CA2254 to a warning and build, or search for Log calls followed by ($". Each one is a log entry without fields.
  2. Name placeholders after what they holdUse PascalCase names that match the fields you'll search on, such as {OrderId} and {UserId}, and keep the same name for the same value across the codebase, so one filter finds every entry.
  3. Pass exceptions as exceptionsWrite logger.LogError(ex, "Payment failed for order {OrderId}", orderId), not $"... {ex.Message}". The exception parameter keeps the type and stack trace; an interpolated message keeps one line of text.
  4. Generate the hot pathsFor log calls inside loops, per-request middleware and anything at Debug or Trace level, declare [LoggerMessage] methods in a partial class and call those instead.

Key takeaways

  • A message template reaches the logger as a constant plus named values; an interpolated string reaches it as finished text.
  • Only templates give log stores fields to filter, group and count on, and a stable {OriginalFormat} per event.
  • With Log{Level} methods, values match placeholders by position; the source generator matches them by name and checks at compile time.
  • Interpolation formats even when the level is off; [LoggerMessage] checks IsEnabled first and avoids boxing, but neither skips evaluating your arguments.

📚 المصادر

  1. Logging in C# and .NET — Microsoft Learn
  2. Compile-time logging source generation — Microsoft Learn
  3. CA2254: Template should be a static expression — Microsoft Learn
  4. CA1848: Use the LoggerMessage delegates — Microsoft Learn

التعليقات (0)