Structured logging in .NET: message templates with named placeholders, how LogValues keeps the template and arguments separately, why $"..." interpolation destroys properties and allocates even when filtered (CA2254), the @ and $ destructuring hints in Serilog, KQL queries over customDimensions, cardinality and naming conventions.
Structured logging records an event: a constant message template plus named properties, instead of a pre-built string. In logger.LogInformation("Order {OrderId} placed in {ElapsedMs} ms", id, ms), the provider gets the template and the values separately, so OrderId and ElapsedMs become queryable fields (Application Insights customDimensions, OpenTelemetry attributes, Seq properties).
With string interpolation ($"Order {id} placed") the provider only sees a finished string: no properties, a different message every time, and the string is built even when the level is disabled. Analyser CA2254 warns about this.
The trade-off: templates take discipline in naming, but they turn logs from text you grep into data you can filter, group and alert on.
"Structured logging means every log entry is an event with a fixed shape: a message template that never changes, plus named properties. When I write
logger.LogInformation("Order {OrderId} placed for {CustomerId} in {ElapsedMs} ms", order.Id, customer.Id, elapsed),Microsoft.Extensions.Loggingdoesn't build the string up front. It passes the provider a state object that holds the template and the three values. The console can still render a nice sentence, but OpenTelemetry or Application Insights storesOrderId,CustomerIdandElapsedMsas separate fields, plus the original template.That changes what I can do with the logs. I can run a KQL query like
traces | where customDimensions.CustomerId == 'C-123', or group by the template to see which events are most frequent, or chartElapsedMspercentiles. If someone writes$"Order {order.Id} placed", all of that is gone: it's one opaque string, every line is unique, and the interpolation and its allocations run even when Information is filtered out. That's what analyser CA2254 is about: the template should be constant.The mistake I see, apart from interpolation, is inconsistent names:
OrderIdin one class,orderIDin another,Idin a third, so no single query finds every event for an order. I agree a short list of property names for the team's key concepts. Structured logging is cheap to start and painful to retrofit, so get the templates right from the first line of code."
| Message template | String interpolation | |
|---|---|---|
| What the provider receives | Template + argument values | One finished string |
| Queryable properties | Yes (OrderId, ElapsedMs) |
No |
| Group identical events | Yes, by {OriginalFormat} |
No, every message differs |
| Cost when level is disabled | Arguments evaluated, array allocated, no formatting | Full string built and thrown away |
| Analyser | – | CA2254 |
| Rule | Example |
|---|---|
| PascalCase, no spaces | {OrderId} not {order id} |
| Same concept, same name everywhere | CustomerId in every service |
| Units in the name | {ElapsedMs}, {SizeBytes} |
| Low-cardinality values for things you group by | {Outcome} = Success/Failed |
| No secrets or personal data | never {Password}, {Email} |
After converting about [200] interpolated log calls in a payments service to templates with agreed property names, the team replaced a [15]-minute log-grepping routine during incidents with a saved KQL query keyed on PaymentId, and could alert on the count of the Payment {PaymentId} declined by {Gateway} template per gateway.
Checks whether the candidate understands what makes logs queryable and why interpolation in log calls is a real problem, not a style nit.
Green flags
Red flags
ex.Message in the template.logger.LogInformation("Order {OrderId} placed in {ElapsedMs} ms", 42, 18.4)
│ LoggerExtensions.Log → new FormattedLogValues(template, args)
▼
ILogger.Log<FormattedLogValues>(level, eventId, state, exception, formatter)
│
├─ state as IReadOnlyList<KeyValuePair<string, object?>>:
│ ["OrderId"] = 42
│ ["ElapsedMs"] = 18.4
│ ["{OriginalFormat}"] = "Order {OrderId} placed in {ElapsedMs} ms"
│
└─ formatter(state, ex) → "Order 42 placed in 18.4 ms" (only if a provider asks)
The template is parsed once and cached (LogValuesFormatter, in a bounded cache), so a constant template is cheap; a template that changes on every call defeats the cache.
Placeholders are bound to arguments by position, not by name. "{CustomerId} bought {OrderId}" with (orderId, customerId) silently swaps them. The names only label the values. Keep the placeholder count equal to the argument count; the [LoggerMessage] generator checks this at compile time, ordinary calls do not.
| Back end | Where you find OrderId |
|---|---|
| Application Insights (classic SDK or Azure Monitor distro) | traces.customDimensions.OrderId |
| OpenTelemetry (OTLP) | Log record attributes |
| Seq | Event properties |
| JSON console | State object with each property |
A KQL example:
traces
| where timestamp > ago(1h)
| where customDimensions.OriginalFormat == "Order {OrderId} placed in {ElapsedMs} ms"
| summarize p95 = percentile(todouble(customDimensions.ElapsedMs), 95) by bin(timestamp, 5m)
The built-in formatter calls ToString() on complex objects (with format specifiers such as {Total:C} supported). Serilog adds {@Order} to serialise an object's properties and {$Order} to force ToString(); those hints are Serilog features and the built-in providers ignore them. Logging whole objects is risky anyway: it can leak personal data and blow up storage.
Every property is stored and indexed. Unique values (GUIDs) are fine for lookups; don't use them in metric dimensions. Large values (request bodies) multiply ingestion cost. Log what you would query.
CA2254 fires when the template argument isn't a constant, for example an interpolated string or concatenation. It is off by default as a warning in some project templates; enable it (and CA1848, which suggests LoggerMessage) in .editorconfig so the build enforces structured logging.
State output.dotnet_diagnostic.CA2254.severity = warning in .editorconfig and build a project with interpolated log calls.customDimensions.OriginalFormat to find your noisiest event.Before and after: interpolation versus a message template with consistent property names.
namespace Shop.Payments;
public sealed record Payment(Guid Id, string CustomerId, decimal Amount, string Gateway);
public sealed class PaymentProcessor(ILogger<PaymentProcessor> logger)
{
public void Before(Payment p, TimeSpan elapsed)
{
// CA2254: one unique string per call, no properties, built even if Information is off
logger.LogInformation($"Payment {p.Id} for {p.CustomerId} took {elapsed.TotalMilliseconds} ms");
}
public void After(Payment p, TimeSpan elapsed)
{
// Constant template: PaymentId, CustomerId, Gateway, ElapsedMs become queryable properties
logger.LogInformation(
"Payment {PaymentId} for {CustomerId} via {Gateway} took {ElapsedMs} ms",
p.Id, p.CustomerId, p.Gateway, elapsed.TotalMilliseconds);
}
public void Declined(Payment p, string reason, Exception? ex = null)
{
// Exception goes in the exception parameter, not in the message
logger.LogWarning(ex, "Payment {PaymentId} declined by {Gateway}: {DeclineReason}", p.Id, p.Gateway, reason);
}
}
Enforcing it in the build:
# .editorconfig
[*.cs]
dotnet_diagnostic.CA2254.severity = warning # template should be a static expression
dotnet_diagnostic.CA1848.severity = suggestion # consider LoggerMessage for hot paths
$"..." in log calls. Why it is wrong: Properties are lost, every message is unique, and the string is built even when filtered out. Instead: Use a constant template with named placeholders.[LoggerMessage] which checks at compile time."Failed: {Error}", ex.Message). Why it is wrong: The stack trace and exception type are lost from the exception fields. Instead: Pass ex as the first argument.{@Order} destructuring with the built-in providers. Why it is wrong: It is a Serilog feature; the built-in formatter just calls ToString(). Instead: Log specific properties, or use the provider that supports it.Structured logging is really a schema decision. The template is the event type and the properties are its columns, so I treat them with the same care as a database schema: stable names, documented key properties, and a review rule against interpolation. Once traces exist (OpenTelemetry), I put fewer identifiers in each message, because TraceId and SpanId already connect the events, and keep properties for the things I filter on.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Templates with named properties | All application logging | Naming discipline | – |
[LoggerMessage] generated methods |
Hot paths, shared event catalogue | More code per event | One-off debug lines |
| Logging whole objects | Short-lived local debugging | PII risk, storage | Production |
| Plain strings | Never for application events | Lost queryability | Always avoid |
$"Hello {name}" is compiled, not parsed at run time. With a string target, C# 10+ uses DefaultInterpolatedStringHandler, which formats each hole straight into a pooled buffer without boxing, then allocates the final string once. Holes take alignment and format ({total,10:C}), and formatting uses the current culture, so for machine-readable text I use string.Create(CultureInfo.InvariantCulture, $"..."). Assigned to FormattableString, it keeps the format and arguments separate, which is how EF Core's FromSql($"...") turns holes into SQL parameters. Raw $$""" strings help with JSON. Two traps: interpolating into raw SQL causes SQL injection, and interpolating into log templates destroys structured logging.
A source generator is a compiler plug-in that reads your code (usually a marker attribute on a partial declaration) and adds new C# files to the compilation; it can never change or delete your code. .NET ships several: System.Text.Json ([JsonSerializable] on a JsonSerializerContext) for reflection-free serialisation, [GeneratedRegex] for regex compiled to C# at build time, [LoggerMessage] for allocation-free structured logging, [LibraryImport] for P/Invoke marshalling, and in ASP.NET Core the configuration binding and Request Delegate generators that replace reflection in Bind/Get<T> and minimal APIs. They improve startup, cut allocations and make code trim and Native AOT safe. Inspect output under Dependencies, Analyzers in the IDE, or set EmitCompilerGeneratedFiles to write the files to obj.
Treat logs as a data store that attackers and too many staff can read. Never log secrets (passwords, tokens, Authorization headers, connection strings, card numbers) and keep personal information out: log identifiers like CustomerId, not names, emails or request bodies.
Enforce it in code rather than by memory: Microsoft.Extensions.Compliance.Redaction lets you classify fields with attributes, map classifications to redactors (erase, or HMAC for a stable pseudonym) with AddRedaction, and apply them to logs with EnableRedaction. Use header allowlists in HTTP logging.
In Australia, APP 11 requires reasonable steps to protect personal information and APP 11.2 requires destroying or de-identifying it when no longer needed, so retention matters, and a leaked log store can be a notifiable data breach. The trade-off: less detail in logs versus a smaller breach surface.
Last updated 23 Nov 2026.