📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is structured logging? Explain message templates versus string interpolation (and the CA2254 warning), how named placeholders become properties, and why this matters when you query logs in Application Insights or Seq.

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.

Intermediate Theory Intermediate application-insights aspnet-core kql logging message-templates structured-logging

🎯 Key points

  • Structured log = event with a constant message template plus named properties, not just a string
  • Placeholders are matched to arguments by position; names become property keys ({OrderId} → OrderId)
  • $"..." interpolation produces one string: properties lost, template varies per call, formatting happens even if the level is disabled
  • CA2254: the template should be a constant so every occurrence groups under one template
  • Properties land in Application Insights customDimensions / OTel attributes, queryable with KQL (where customDimensions.OrderId == ...)
  • The {OriginalFormat} property holds the template, so you can count occurrences of the same event
  • Keep property names consistent (PascalCase, same name for the same concept) and avoid logging huge objects
  • Serilog-style {@Order} destructuring is not supported by the built-in formatter; it is a provider feature

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.Logging doesn'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 stores OrderId, CustomerId and ElapsedMs as 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 chart ElapsedMs percentiles. 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: OrderId in one class, orderID in another, Id in 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."


Template vs interpolation

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

Naming conventions that pay off

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}

Production example

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.

🔍 What the interviewer is checking

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

  • Explains template plus properties and where they appear (customDimensions, attributes).
  • Knows interpolation allocates even when filtered, and names CA2254.
  • Mentions positional binding and consistent property names.
  • Talks about querying with KQL or Seq and grouping by template.

Red flags

  • Thinks interpolation and templates are equivalent.
  • Logs exceptions via ex.Message in the template.
  • Proposes logging entire request bodies for convenience.

📚 Learn in depth

1. What actually travels to the provider

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.

2. Positional binding

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.

3. Where the properties end up

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)

4. Formatting and destructuring

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.

5. Cardinality and cost

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.

6. What CA2254 checks

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.

Try it yourself

  1. Log the same event with a template and with interpolation to the JSON console; compare the State output.
  2. Enable dotnet_diagnostic.CA2254.severity = warning in .editorconfig and build a project with interpolated log calls.
  3. Send logs to a local Seq container and filter by a property.
  4. Swap the argument order in a two-placeholder template and see the wrong values appear.
  5. With the Azure Monitor distro, write a KQL query grouping by customDimensions.OriginalFormat to find your noisiest event.

💻 Code

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

⚠ Common mistakes

  • Mistake: Using $"..." 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.
  • Mistake: Thinking placeholders bind by name. Why it is wrong: Binding is positional, so swapped arguments log wrong values under the right names. Instead: Keep order aligned, or use [LoggerMessage] which checks at compile time.
  • Mistake: Different names for the same concept across services. Why it is wrong: No single query finds all events for an order or customer. Instead: Agree a property-name list for key identifiers.
  • Mistake: Putting the exception message in the template ("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.
  • Mistake: Logging whole request objects or DTOs as a property. Why it is wrong: Personal data leaks and ingestion cost explodes. Instead: Log the identifiers and the few fields you query.
  • Mistake: Expecting {@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.
  • Mistake: Concatenating strings to build a template. Why it is wrong: Same as interpolation, and it defeats the template cache. Instead: Keep templates as literals.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions that interpolation allocates even when the level is disabled. Why: Checks they understand how C# interpolation and interpolated string handlers work, and why the logging API doesn't use them.
    How to answer

    $"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.

  2. When: Candidate mentions positional binding mistakes or CA1848. Why: Checks they know the LoggerMessage source generator and how it enforces templates at compile time.
    How to answer

    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.

  3. When: Candidate mentions logging identifiers or warns against logging whole objects. Why: Checks they know which properties must never be logged and how redaction works on structured properties.
    How to answer

    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.

↩ Usually asked after

More in Logging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me