Volume 7 · Chapter 7 — Advanced .NET Engineering, Performance & Production Excellence
Logging Architecture
7.1 Introduction
Logging is the most detailed observability signal and the one engineers reach for first during an incident. But naive logging - unstructured strings, no correlation, secrets in plaintext, or logging everything - becomes a cost centre and a liability rather than an asset. A good logging architecture is structured, correlated, secure, and cost-aware, so that the log you need is findable in seconds and the logs you do not need are not paid for.
7.2 Structured Logging
Structured logging records events as data - a message template plus named properties - rather than pre-formatted strings. This makes logs queryable: you can filter byTransactionIdor aggregate byServiceinstead of grepping text. The .NETILoggerabstraction is structured by design when you use message templates with named placeholders.
// Named placeholders become queryable fields - not string concatenation.
_logger.LogInformation(
"Payment {PaymentId} for {Amount} {Currency} failed: {Reason}",
payment.Id, payment.Amount, payment.Currency, reason);
// Anti-pattern: interpolation destroys structure and pays formatting cost even
// when the level is disabled.
// _logger.LogInformation($"Payment {payment.Id} failed: {reason}");
7.3 Serilog and the Provider Model
ILoggeris the facade; providers do the work. Serilog is the common choice, adding sinks (where logs go), enrichers (extra context on every event), and filters. A typical setup enriches every log with the machine, environment, and trace id, and writes to console (for container log scraping) plus a centralized sink.
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Service", "PaymentsApi")
.Enrich.WithSpan() // adds TraceId/SpanId
.WriteTo.Console(new JsonFormatter()) // structured JSON for collectors
.WriteTo.OpenTelemetry() // ship to central backend
.CreateLogger();
7.4 Log Levels and When to Use Them
| Level | Use for | Production default |
|---|---|---|
| Trace/Debug | Fine-grained developer diagnostics | Off (enable on demand) |
| Information | Significant business events | On (sparingly) |
| Warning | Recoverable anomalies, degraded paths | On |
| Error | Failures needing attention | On |
| Critical | System-threatening failures | On (alert) |
7.5 Correlation Across Services
The single most valuable field in distributed logs is a correlation/trace id that ties every log line from one request together, across services. With OpenTelemetry the trace id is ambient; enriching every log with it means a single query returns the entire story of a request wherever it ran.
sequenceDiagram
autonumber
participant C as Client
participant GW as Gateway
participant Pay as Payments
participant Led as Ledger
C->>GW: request (generate/accept trace id T)
GW->>Pay: call (propagate T)
Pay->>Led: call (propagate T)
Note over GW,Led: Every log line carries TraceId=T
Led-->>Pay: log "posted entry" {TraceId:T}
Pay-->>GW: log "payment ok" {TraceId:T}
GW-->>C: response 7.6 Protecting Sensitive Data
Logs are a frequent source of data breaches and compliance violations. Passwords, tokens, full card numbers (PCI), and personal data (GDPR) must never be logged. Enforce this with destructuring policies that redact known-sensitive properties, code review, and, ideally, typed wrappers that render as***.
// Redact sensitive members centrally so no call site can leak them.
Log.Logger = new LoggerConfiguration()
.Destructure.ByTransforming<CardDetails>(c =>
new { c.Last4, Number = "****-****-****-" + c.Last4 })
.CreateLogger();
7.7 Performance and Cost
Logging is not free: string formatting, serialization, and sink I/O all cost CPU and money. Use appropriate levels (Trace/Debug off in production), rely onILogger’s level checks and high-performanceLoggerMessagesource generators for hot paths, prefer asynchronous /batched sinks so logging does not block request threads, and sample or cap high-volume events. Centralized log storage is billed by volume, so noisy “success” logging is a recurring, avoidable expense.
// Source-generated logging: no allocation/formatting when the level is disabled.
public static partial class Log
{
[LoggerMessage(Level = LogLevel.Warning,
Message = "Retry {Attempt} for {Operation} after {Delay}ms")]
public static partial void Retrying(ILogger logger, int attempt, string operation, long delay);
}
Why is structured logging preferred over plain-text logging in enterprise systems?
Because structured logs are data, not prose. Each event carries named fields, so you can query, filter, and aggregate - “show all failures forTransactionId=123” or “count errors per service per minute” - which is impossible to do reliably by grepping free-text. Structured logs correlate across services via shared fields like the trace id, feed dashboards and alerts directly, and survive message-wording changes because you filter on fields, not substrings. In .NET you get this for free by using message templates with named placeholders instead of string interpolation.
Why should you use message templates instead of string interpolation with ILogger?
Two reasons: structure and cost. A template like"Payment {Id} failed"preservesIdas a queryable field in the sink, whereas$"Payment {id} failed"collapses it into an opaque string. And interpolation builds the full string eagerly, paying the formatting and allocation cost even when that log level is disabled; the template form defers formatting until the logger confirms the level is enabled, and withLoggerMessagesource generation it allocates nothing on the disabled path. So templates are both more useful and faster.
How do you keep sensitive data out of logs?
Defense in depth. Establish a clear policy on what is never logged (credentials, tokens, full PANs, personal data), and enforce it structurally rather than relying on discipline: central destructuring/redaction policies that mask known-sensitive properties, typed wrappers whoseToStringrenders masked values, and avoiding logging whole request/response bodies. Add automated checks (linters or tests scanning for risky patterns) and code review focus. Because logs flow to centralized stores and third parties, a single leaked secret can become a compliance incident, so the safe default is to log identifiers and outcomes, not payloads.
Logging costs have exploded and are now a major line item. How do you bring them under control without losing debuggability?
Runaway log cost is almost always volume from low-value events. I’d start by measuring which services and event types dominate the bill, then attack the biggest sources: raise production levels so Trace/Debug and routine “success” chatter are off by default, replacing them with metrics (a counter is far cheaper than a log line for “it worked”). I’d keep rich logging for failures and key business events, add sampling for high-frequency informational logs, and ensure we log identifiers and outcomes rather than full payloads. Trace ids preserve debuggability because a single failing request is still fully reconstructable. I’d also set retention tiers - hot storage for recent, cheap cold storage for older - and put a cardinality/volume budget in place with alerts. The principle is that observability value comes from the right logs, not the most logs.
How do you design a logging standard that works consistently across dozens of services and teams?
I make the correct thing the default and the easy thing. That means a shared logging library or template that every service adopts: structured logging viaILogger, mandatory enrichment with trace id, service name, and environment, a JSON format the central collector understands, and built-in redaction of sensitive types. I standardize level semantics so “Error” means the same thing everywhere, and ship baseline configuration (production levels, async sinks) so teams do not each reinvent it. I pair it with guidance on what to log (outcomes and identifiers, not payloads) and automated checks in CI. Consistency is what lets an on-call engineer read any service’s logs during an incident without learning a bespoke scheme, and centralizing it in a shared library means improvements and security fixes roll out everywhere at once.
7.8 Banking Enterprise Scenario
A bank standardizes logging through a shared library: structuredILoggeroutput enriched with trace id, service, and environment, formatted as JSON to a central platform, with card and personal data redacted by a destructuring policy. Production runs at Information and above, with routine successes tracked as metrics instead of logs to control cost. When a transfer fails, an engineer queries the trace id and instantly sees the correlated lines from gateway, payments, and ledger - including the redacted card’s last four digits - pinpointing the failing downstream without ever exposing sensitive data.
Chapter Revision Notes
- Log structured data (message templates), not interpolated strings.
- Enrich every log with a trace/correlation id to tie requests together.
- Never log secrets or personal data - enforce redaction centrally.
- Set production levels sensibly; prefer metrics over high-volume info logs.
- Use async sinks and LoggerMessage source generators on hot paths.
- Treat log volume as a real cost with retention tiers and budgets.