
Why ILogger Wants Message Templates, Not String Interpolation
- كاتب موثّق
- .NET 10
محتويات المقال
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
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.
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.
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):
{ "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
$"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
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
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
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}"); }}public sealed partial class PaymentService(ILogger<PaymentService> logger){ public void OnDeclined(int orderId, string reason, Cart cart) { LogDeclined(orderId, reason); LogCart(cart); // checks IsEnabled(Debug) before any work } // The generator writes the bodies, using the logger parameter above [LoggerMessage(Level = LogLevel.Warning, Message = "Payment declined for order {OrderId}: {Reason}")] partial void LogDeclined(int orderId, string reason); [LoggerMessage(Level = LogLevel.Debug, Message = "Cart at decline: {Cart}")] partial void LogCart(Cart cart);}[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] | |
|---|---|---|---|
OrderId, Reason | OrderId, Reason | ||
{OriginalFormat} | |||
ToString | IsEnabled first | ||
How to apply it in your project
Find the interpolated calls Raise CA2254 to a warning and build, or search for Logcalls followed by($". Each one is a log entry without fields.Name placeholders after what they hold Use 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.Pass exceptions as exceptions Write 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.Generate the hot paths For log calls inside loops, per-request middleware and anything at Debug or Trace level, declare [LoggerMessage]methods in apartialclass 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]checksIsEnabledfirst and avoids boxing, but neither skips evaluating your arguments.
التعليقات (0)