Structured logging
Structured logging
Structured logging records an event with a message template and named data values. ILogger is the abstraction used by application code; providers decide where and how records are written. A fixed template lets a log system group similar events and query fields without extracting them from arbitrary prose.
Proposed baseline: .NET SDK 10.0.404, net10.0 / C# 14. Requires installed ASP.NET Core 10 shared framework/reference pack (FrameworkReference Microsoft.AspNetCore.App); the examples are console programs, not web servers. C# results are reasoned, not executed. See the accompanying independent project fixture; approve dependencies and environment before restoring or building.
Write a structured event
Use a JSON console provider for a synthetic order. The exact JSON envelope varies with formatter and settings.
using Microsoft.Extensions.Logging;using var factory = LoggerFactory.Create(b => b.AddJsonConsole().SetMinimumLevel(LogLevel.Information));var logger = factory.CreateLogger("Orders");logger.LogInformation("Order {OrderId} has {ItemCount} items", "DEMO-7", 3);The placeholders name fields; arguments are assigned by position. The provider may retain both the formatted message and structured state. Interpolating a string first loses these separate template values.
Expected observation (reasoned, not executed):
Information event with OrderId=DEMO-7 and ItemCount=3Filter by severity
The threshold is Warning, so Debug and Information do not reach the configured provider.
using Microsoft.Extensions.Logging;using var factory = LoggerFactory.Create(b => b.AddSimpleConsole().SetMinimumLevel(LogLevel.Warning));var logger = factory.CreateLogger("Inventory");logger.LogDebug("Checking stock");logger.LogInformation("Stock read");logger.LogWarning("Stock below threshold: {Count}", 2);Severity expresses urgency and filter policy controls emitted records. Provider-specific category rules can override general thresholds.
Expected observation (reasoned, not executed):
One Warning event: Stock below threshold: 2Attach a scope to related events
Enable scopes explicitly on the JSON formatter; use a synthetic correlation value rather than a customer identifier.
using System.Collections.Generic;using Microsoft.Extensions.Logging;using var factory = LoggerFactory.Create(b => b.AddJsonConsole(o => o.IncludeScopes = true).SetMinimumLevel(LogLevel.Information));var logger = factory.CreateLogger("Jobs");using (logger.BeginScope(new Dictionary<string, object> { ["JobId"] = "JOB-4" })){ logger.LogInformation("Job started"); logger.LogInformation("Job finished");}logger.LogInformation("Idle");Scope data supplies shared context for a bounded operation. Dispose the scope to avoid attaching context to unrelated events. The output envelope is provider-specific.
Expected observation (reasoned, not executed):
Two job events include JobId=JOB-4 in scope; Idle is outside that scopeCommon mistakes and edge cases
Use stable event IDs and templates where helpful. Log expected business failures at a level appropriate to their impact; not every unsuccessful operation is a critical error. Pass an exception to the exception overload only after reviewing its contents and logging policy. Never log passwords, tokens, full connection strings or sensitive payloads. Scope support and field serialization depend on the provider. Logging is not a substitute for metrics, tracing or durable audit controls.
Practice and recap
An import job processes 12 rows and rejects 2. Design a stable template, named fields and a scope. Explain which values must never be logged.
Hint: Use counts, not raw records.
Learning objective: Separate stable message template and values. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structured logging — knowledge check
Apply the lesson concepts to the following scenarios.
What is the benefit of a fixed template?
Which event reaches a Warning threshold in the example?
What ends a BeginScope context?
How are template arguments associated?
Which is safe for a synthetic import summary?