Text Logging vs Structured Logging
Traditional Text Logging
With traditional logging, you might write:Structured Logging with Serilog
With Serilog’s structured logging approach:UserName and IpAddress are first-class properties that can be:
- Queried and filtered efficiently
- Indexed by log aggregation systems
- Analyzed without text parsing
The message template
"User {UserName} logged in from {IpAddress}" remains constant, making it easy to identify all occurrences of the same event type.How Serilog Captures Structure
Serilog uses message templates to capture both a human-readable message and structured data. Each log event (represented by theLogEvent class) contains:
- Timestamp: When the event occurred
- Level: The severity level (Information, Warning, Error, etc.)
- MessageTemplate: The template string with placeholders
- Properties: A dictionary of captured property values
- Exception: An optional exception object
- TraceId/SpanId: Optional distributed tracing identifiers
Events/LogEvent.cs:23-45):
Benefits of Structured Logging
1. Powerful Querying
Query logs by specific property values:2. Consistent Event Types
The same message template identifies the same type of event, regardless of parameter values:"User {UserName} logged in from {IpAddress}"
3. Type Preservation
Structured properties preserve their original types:OrderId is stored as an integer and Amount as a decimal, not as strings.
4. Reduced Storage and Better Compression
Message templates are stored once and reused, while only property values vary:Working with Complex Objects
Structured logging really shines when capturing complex objects:The
@ and $ prefixes control how objects are captured. See Message Templates for more details.Best Practices
- Use named placeholders:
{UserName}instead of positional{0} - Keep templates constant: Don’t interpolate values into the template itself
- Use semantic property names:
{OrderId}is better than{Id} - Leverage destructuring: Use
@for complex objects you want to query - Preserve types: Let Serilog capture the original type rather than converting to strings
Structured logging is most valuable when paired with a log aggregation system that can index and query structured data, such as Elasticsearch, Seq, or Application Insights.