In ASP.NET Core, why pass a message template with arguments to logger.LogInformation instead of an interpolated $"..." string, and how do placeholders bind?
answer
- named values survive into log state
- {OriginalFormat} keeps the template
- interpolation formats even when filtered
- placeholders bind by position, not name
- CA2254 and CA2017
basics
~20 sA template such as "Picked {Sku} for order {OrderId}" keeps Sku, OrderId and the template as named values that providers can emit as fields. An interpolated string arrives as one finished text, built even when the level is filtered out.
solid answer
~40 s`LogInformation("Picked {Sku} for order {OrderId}", sku, orderId)` hands the logger a state object that is a list of key/value pairs: `Sku`, `OrderId` and `{OriginalFormat}` holding the unrendered template. A structured provider such as the JSON console formatter writes those as separate fields (an `int` stays a number), and every pick shares one template you can group by. An interpolated `$"Picked {sku} for order {orderId}"` is rendered by C# before the call, so the state carries only `{OriginalFormat}` containing the finished text, and the formatting cost is paid even when `Information` is filtered out. Placeholders bind **by position**: the names label the values but never match argument names, so swapping arguments silently mislabels them. The analyzers help: CA2254 flags a non-constant template and CA2017 a placeholder/argument count mismatch.
code
csharp · 13 linespublic sealed class PickConfirmation(ILogger<PickConfirmation> logger)
{
public void Confirm(string sku, int orderId, decimal weightKg)
{
// Structured: Sku, OrderId, WeightKg and {OriginalFormat} reach the provider
logger.LogInformation(
"Picked {Sku} for order {OrderId}, {WeightKg:0.00} kg",
sku, orderId, weightKg);
// Flattened: only {OriginalFormat} holding the finished sentence (CA2254)
logger.LogInformation($"Picked {sku} for order {orderId}");
}
}go deeper
Recall that LogInformation takes a template with {Name} placeholders and the values as extra arguments, and that a $ string should not be passed instead.
Explain what the state carries in each form, {OriginalFormat} included, why binding is positional, and which analyzers (CA2254, CA2017) catch the mistakes.
Show how template discipline makes logs queryable by OrderId or Sku, and point out the residual allocation the template form still has on hot paths.
Treat placeholder names as a schema shared by every team's dashboards and alerts, and decide how naming is reviewed and enforced across services.
## Two ways to write the same line In a picking service that confirms every scanned item, both calls below print the same sentence to a plain console: ```csharp logger.LogInformation("Picked {Sku} for order {OrderId}", sku, orderId); // message template logger.LogInformation($"Picked {sku} for order {orderId}"); // interpolated string ``` They are not the same log entry. The `LogInformation(string? message, params object?[] args)` extension in `Microsoft.Extensions.Logging` wraps the message and the arguments in an internal `FormattedLogValues` state object and passes it to `ILogger.Log<TState>`. What that state contains decides what any provider can do with the entry. ## What the template keeps `FormattedLogValues` implements `IReadOnlyList<KeyValuePair<string, object?>>`. For the template form it holds: - `Sku` with the original argument object; - `OrderId` with the original `int`; - `{OriginalFormat}` with the unrendered text `Picked {Sku} for order {OrderId}`, always the last pair. The JSON console formatter (`AddJsonConsole`) enumerates that list into a `State` object, so the line reads roughly `"State": {"Sku": "SKU-4471", "OrderId": 90211, "{OriginalFormat}": "Picked {Sku} for order {OrderId}"}` with `OrderId` written as a JSON number. A log store can then filter on `OrderId = 90211` or count entries per template without parsing sentences. ## What interpolation loses With `$"..."`, the C# compiler builds the final string before `LogInformation` is even entered. The extension receives a message and no arguments, so: 1. The state holds a single pair, `{OriginalFormat}`, whose value is the rendered sentence; there is no `Sku` or `OrderId` field. 2. Every pick produces a different "template", so grouping by template groups nothing. 3. The string is built on every call, even when the category's minimum level is `Warning` and the entry is thrown away. With a template, rendering the sentence is deferred until a provider actually writes the entry. The template form is not free either: the `params` array is allocated and value types are boxed before the level is checked, which is the reason the hot-path tools (`IsEnabled`, `[LoggerMessage]`) exist. ## How placeholders bind The template is parsed once by `LogValuesFormatter` and cached per distinct template string. Parsing assigns each `{Name}` an **index in order of appearance**; the names become keys, but they are never matched against argument names: ```csharp logger.LogInformation("Bin {Bin} holds order {OrderId}", orderId, bin); // Bin = the orderId value, OrderId = the bin value: wrong labels, no exception ``` Other template rules worth knowing: | Template feature | Example | Effect | |---|---|---| | Format specifier | `{Weight:0.00}` | the value is formatted with that format when rendered | | Escaped brace | `{{` and `}}` | a literal brace in the output | | Same name twice | `{OrderId} ... {OrderId}` | two positions, two arguments needed | | Fewer arguments than holes | `"{Sku} {Bin}", sku` | the analyzer warns (CA2017) | ## The analyzers that police it - **CA2254** "Template should be a static expression": reported (as a suggestion in .NET 10) when the template is not a constant, which is exactly what an interpolated string or a concatenation is. - **CA2017** "Parameter count mismatch": a warning when the number of placeholders and arguments differ. - **CA1727** "Use PascalCase for named placeholders": off by default; it keeps keys consistent across a code base. ## Practical guidance - Keep templates constant and name placeholders after what the value is (`OrderId`, not `id`), because those names become field names in every structured sink. - Pass the exception as the first argument of the `Exception` overload, not as a placeholder value, so providers record it as the entry's exception. - Do not build a template from data: if the template string changes per call the formatter cache stops adding entries after 1,024 distinct templates, and every new string is parsed again on each call.
- Does the template form avoid all cost when the Information level is filtered out?No. The `LogInformation` extension still allocates the `params object?[]` array, boxes value-type arguments and creates the state before `Logger.Log` checks each provider's minimum level. What it avoids is rendering the sentence. On hot paths, `[LoggerMessage]` methods or an `IsEnabled` guard remove the remaining work.
- What happens if code builds the template string from data while still passing arguments?Each distinct string is parsed as a new template. `FormattedLogValues` caches parsed templates only until it holds 1,024 of them; after that, an unseen template is parsed again on every call. The log store also sees thousands of distinct templates, and CA2254 flags the call.
- Interpolated strings are cheaper because the logger skips template parsing.
- Placeholder names are matched to argument names, so order does not matter.
- An interpolated message still exposes OrderId as a separate field.
- The template form costs nothing at all when the level is disabled.
- Message templates only matter if you use Serilog.