dotnet-structured-logging
Log pipeline design and operations for .NET distributed systems. Covers log aggregation architecture (ELK, Seq, Grafana
Loki), structured query patterns for each platform, log sampling and volume management strategies, PII scrubbing and
destructuring policies, and cross-service correlation beyond single-service log scopes. This skill addresses what
happens after log emission -- the pipeline, query, and operations layer.
Scope
- Log aggregation architecture (ELK, Seq, Grafana Loki)
- Structured query patterns per platform
- Log sampling and volume management strategies
- PII scrubbing and destructuring policies
- Cross-service correlation and distributed context
Out of scope
- Log emission mechanics (Serilog/NLog/MEL, LoggerMessage, sinks, OTel export) -- see [skill:dotnet-observability]
- Application configuration and options pattern -- see [skill:dotnet-csharp-configuration]
- Distributed tracing setup and trace context propagation -- see [skill:dotnet-observability]
Cross-references: [skill:dotnet-observability] for log emission, Serilog/MEL configuration, and OpenTelemetry logging
export, [skill:dotnet-csharp-configuration] for appsettings.json configuration patterns used in log pipeline setup.
Log Aggregation Architecture
Architecture Options
| Platform |
Ingest |
Storage |
Query |
Best for |
| ELK (Elasticsearch, Logstash, Kibana) |
Logstash / Filebeat |
Elasticsearch |
KQL in Kibana |
Large-scale, flexible schema, full-text search |
| Seq |
HTTP API / Serilog sink |
Built-in |
Seq signal expressions |
.NET-native, developer-friendly, structured queries |
| Grafana Loki |
Promtail / OTel Collector |
Loki (label-indexed) |
LogQL |
Cost-effective, Grafana ecosystem, label-based queries |
| Azure Monitor |
OTel Collector / Application Insights SDK |
Log Analytics workspace |
KQL (Kusto) |
Azure-native, integrated alerting, cost management |
Recommended Pipeline Patterns
Pattern 1: OTel Collector as central router
App (OTLP) --> OTel Collector --> Elasticsearch / Loki / Azure Monitor
|
+--> Sampling / filtering / PII scrub
```text
The OpenTelemetry Collector acts as a vendor-neutral log router. Applications emit logs via OTLP; the collector handles filtering, sampling, enrichment, and routing to one or more backends. This decouples applications from backend choice.
```yaml
# otel-collector-config.yaml
receivers:
otlp:
protocols:
grpc:
endpoint: "0.0.0.0:4317"
http:
endpoint: "0.0.0.0:4318"
processors:
batch:
timeout: 5s
send_batch_size: 1024
filter:
logs:
exclude:
match_type: strict
bodies:
- "Health check endpoint hit"
exporters:
elasticsearch:
endpoints: ["https://es-cluster:9200"]
logs_index: "app-logs"
loki:
endpoint: "http://loki:3100/loki/api/v1/push"
service:
pipelines:
logs:
receivers: [otlp]
processors: [batch, filter]
exporters: [elasticsearch, loki]
```text
**Pattern 2: Direct sink (smaller deployments)**
```text
App (Serilog) --> Seq / Elasticsearch sink
```text
For smaller systems or development environments, Serilog sinks write directly to the aggregation platform. This avoids the OTel Collector but couples the application to the backend.
### .NET Application OTLP Configuration
For .NET application-side OTLP log export configuration (`builder.Logging.AddOpenTelemetry()`), see [skill:dotnet-observability]. The OTLP endpoint is configured via environment variables (`OTEL_EXPORTER_OTLP_ENDPOINT`), keeping application code backend-agnostic.
---
## Structured Query Patterns
Structured logs store each property as a queryable field. The query syntax differs by platform but the concepts are consistent: filter by property name, value, severity, and time range.
### Kibana KQL (Elasticsearch / ELK)
```text
# Find errors for a specific order
level: "Error" AND OrderId: "abc-123"
# Find slow operations (custom Duration property)
Duration > 5000 AND ServiceName: "order-api"
# Wildcard on message template
message: "Failed to process*" AND NOT level: "Debug"
# Time-scoped with correlation
TraceId: "0af7651916cd43dd8448eb211c80319c" AND @timestamp >= "2025-01-15T10:00:00"
```text
### Seq Signal Expressions
```text
# Find errors for a specific order
@Level = 'Error' and OrderId = 'abc-123'
# Find slow operations
Duration > 5000 and Application = 'order-api'
# Free-text search combined with structured filter
@Message like '%timeout%' and @Level in ['Warning', 'Error']
# Correlation across services
TraceId = '0af7651916cd43dd8448eb211c80319c'
```text
Seq signals are saved queries that trigger alerts. Define signals for recurring patterns (e.g., "Payment failures > 10/min") and attach notification channels.
### Grafana LogQL (Loki)
```text
# Filter by labels then regex on log line
{service_name="order-api"} |= "Error" | json | OrderId="abc-123"
# Structured field extraction and filtering
{service_name="order-api"} | json | Duration > 5000
# Count errors per service over time (for dashboards)
sum(rate({service_name=~".+"} |= "Error" [5m])) by (service_name)
```json
### Azure Monitor KQL (Kusto)
```kusto
// Find errors for a specific order
traces
| where severityLevel >= 3
| where customDimensions.OrderId == "abc-123"
| order by timestamp desc
// Slow operations
traces
| where toint(customDimensions.Duration) > 5000
| where cloud_RoleName == "order-api"
// Cross-service correlation
union traces, exceptions
| where operation_Id == "0af7651916cd43dd8448eb211c80319c"
| order by timestamp asc
```text
---
## Log Sampling and Volume Management
High-throughput systems can generate millions of log events per minute. Without sampling, storage costs and query performance degrade rapidly.
### Sampling Strategies
| Strategy | How it works | Use when |
|----------|-------------|----------|
| **Head-based** | Decide to sample before processing | Consistent per-request; simple to implement |
| **Tail-based** | Decide to sample after processing | Keep all errors/slow requests, drop routine logs |
| **Level-based** | Sample by severity | Always keep Warning+, sample Debug/Info |
| **Dynamic** | Adjust rate based on volume | Handle traffic spikes without config changes |
### OTel Collector Log Filtering
The `filter` processor in the OTel Collector drops log records at the pipeline level before they reach exporters. Use it to exclude noisy low-severity logs and reduce storage volume.
Note: The `tail_sampling` processor operates on **traces** (spans), not logs. For log volume management, use the `filter` and `transform` processors instead.
```yaml
processors:
filter:
logs:
exclude:
match_type: regexp
# Drop Debug and Trace logs at the collector level
severity_texts: ["DEBUG", "TRACE"]
exclude:
match_type: strict
# Exclude health check noise
bodies:
- "Health check endpoint hit"
transform:
log_statements:
- context: log
conditions:
# Keep all Warning+ logs unconditionally
- severity_number >= SEVERITY_NUMBER_WARN
statements: []
```text
### Application-Level Sampling with Serilog
```csharp
// Serilog.Expressions package for conditional log filtering
builder.Host.UseSerilog((context, loggerConfiguration) =>
{
loggerConfiguration
.ReadFrom.Configuration(context.Configuration)
// Drop health check logs entirely
.Filter.ByExcluding("RequestPath = '/health/ready'")
// Sample Debug logs at 10%
.Filter.ByExcluding(
"@Level = 'Debug' and Hash(@i) % 10 != 0");
});
```text
**Key packages:**
```xml
<PackageReference Include="Serilog.Expressions" Version="5.*" />
```xml
### Volume Management Checklist
1. **Set retention policies** per index/stream (e.g., 30 days for Info, 90 days for Error)
2. **Use log level filtering** to suppress noisy framework categories at the source
3. **Exclude health check endpoints** from request logging
4. **Apply index lifecycle management** (ILM in Elasticsearch, retention policies in Loki)
5. **Monitor ingestion rates** and set budget alerts on storage costs
---
## PII Scrubbing and Destructuring Policies
Logs must not contain personally identifiable information (PII) in production. GDPR, HIPAA, and SOC 2 require that sensitive data is masked or excluded from log storage.
### Property-Level Masking with Enrichers
```csharp
// Enricher that masks known-sensitive properties on every log event
public sealed class PiiMaskingEnricher : ILogEventEnricher
{
private static readonly HashSet<string> s_sensitiveKeys = new(
StringComparer.OrdinalIgnoreCase)
{
"Email", "PhoneNumber", "IpAddress",
"CreditCard", "SSN", "Password"
};
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory factory)
{
var propertiesToMask = logEvent.Properties
.Where(p => s_sensitiveKeys.Contains(p.Key))
.Select(p => p.Key)
.ToList();
foreach (var key in propertiesToMask)
{
logEvent.AddOrUpdateProperty(
factory.CreateProperty(key, "***REDACTED***"));
}
}
}
// Registration
loggerConfiguration.Enrich.With<PiiMaskingEnricher>();
```text
### OTel Collector Attribute Processing
```yaml
processors:
attributes:
actions:
# Mask email addresses using regex
- key: user.email
action: update
value: "***@redacted.com"
# Remove sensitive attributes entirely
- key: http.request.header.authorization
action: delete
- key: user.password
action: delete
```text
### PII Scrubbing Checklist
1. **Identify PII fields** -- email, phone, IP, SSN, credit card, auth tokens, cookies
2. **Apply at the earliest point** -- enricher or OTel processor, not at query time
3. **Audit log templates** -- ensure structured log templates do not capture PII as named properties
4. **Test with compliance team** -- validate scrubbing rules against regulatory requirements
5. **Use separate retention** for audit logs that legitimately require PII (with encryption at rest)
---
## Cross-Service Correlation
In distributed systems, a single user request may traverse multiple services. Correlation enables tracing a request across all services and reconstructing the full event timeline.
### W3C Trace Context Correlation
The primary correlation mechanism is the W3C `traceparent` header, which propagates automatically through `HttpClient` when OpenTelemetry instrumentation is configured (see [skill:dotnet-observability]). All log events emitted within a traced request include `TraceId` and `SpanId` properties.
```csharp
// Query all logs for a distributed operation across services
// In Seq:
TraceId = '0af7651916cd43dd8448eb211c80319c'
// In Kibana:
TraceId: "0af7651916cd43dd8448eb211c80319c"
// In Azure Monitor:
traces | where operation_Id == "0af7651916cd43dd8448eb211c80319c"
```text
### Custom Correlation IDs
When trace context is insufficient (e.g., async workflows spanning message queues, batch jobs, or external system callbacks), add custom correlation IDs:
```csharp
// Propagate a business correlation ID through Serilog LogContext
public sealed class CorrelationIdMiddleware(RequestDelegate next)
{
private const string CorrelationHeader = "X-Correlation-Id";
public async Task InvokeAsync(HttpContext context)
{
var correlationId = context.Request.Headers[CorrelationHeader]
.FirstOrDefault() ?? Guid.NewGuid().ToString("N");
context.Response.Headers[CorrelationHeader] = correlationId;
using (LogContext.PushProperty("CorrelationId", correlationId))
{
await next(context);
}
}
}
## Detailed Examples
See [references/detailed-examples.md](references/detailed-examples.md) for complete code samples and advanced patterns.
1---2name: dotnet-structured-logging3category: developer-experience4subcategory: cli5description: Designs log pipelines. Aggregation, structured queries, sampling, PII scrubbing, correlation.6license: MIT7targets: ['*']8tags: [architecture, dotnet, skill]9version: '0.0.1'10author: 'dotnet-agent-harness'11invocable: true12claudecode:13 allowed-tools: ['Read', 'Grep', 'Glob', 'Bash', 'Write', 'Edit']14codexcli:15 short-description: '.NET skill guidance for architecture tasks'16opencode:17 allowed-tools: ['Read', 'Grep', 'Glob', 'Bash', 'Write', 'Edit']18copilot: {}19geminicli: {}20antigravity: {}21---2223# dotnet-structured-logging2425Log pipeline design and operations for .NET distributed systems. Covers log aggregation architecture (ELK, Seq, Grafana26Loki), structured query patterns for each platform, log sampling and volume management strategies, PII scrubbing and27destructuring policies, and cross-service correlation beyond single-service log scopes. This skill addresses what28happens _after_ log emission -- the pipeline, query, and operations layer.2930## Scope3132- Log aggregation architecture (ELK, Seq, Grafana Loki)33- Structured query patterns per platform34- Log sampling and volume management strategies35- PII scrubbing and destructuring policies36- Cross-service correlation and distributed context3738## Out of scope3940- Log emission mechanics (Serilog/NLog/MEL, LoggerMessage, sinks, OTel export) -- see [skill:dotnet-observability]41- Application configuration and options pattern -- see [skill:dotnet-csharp-configuration]42- Distributed tracing setup and trace context propagation -- see [skill:dotnet-observability]4344Cross-references: [skill:dotnet-observability] for log emission, Serilog/MEL configuration, and OpenTelemetry logging45export, [skill:dotnet-csharp-configuration] for appsettings.json configuration patterns used in log pipeline setup.4647---4849## Log Aggregation Architecture5051### Architecture Options5253| Platform | Ingest | Storage | Query | Best for |54| ----------------------------------------- | ----------------------------------------- | ----------------------- | ---------------------- | ------------------------------------------------------ |55| **ELK** (Elasticsearch, Logstash, Kibana) | Logstash / Filebeat | Elasticsearch | KQL in Kibana | Large-scale, flexible schema, full-text search |56| **Seq** | HTTP API / Serilog sink | Built-in | Seq signal expressions | .NET-native, developer-friendly, structured queries |57| **Grafana Loki** | Promtail / OTel Collector | Loki (label-indexed) | LogQL | Cost-effective, Grafana ecosystem, label-based queries |58| **Azure Monitor** | OTel Collector / Application Insights SDK | Log Analytics workspace | KQL (Kusto) | Azure-native, integrated alerting, cost management |5960### Recommended Pipeline Patterns6162#### Pattern 1: OTel Collector as central router6364````text6566App (OTLP) --> OTel Collector --> Elasticsearch / Loki / Azure Monitor67 |68 +--> Sampling / filtering / PII scrub6970```text7172The OpenTelemetry Collector acts as a vendor-neutral log router. Applications emit logs via OTLP; the collector handles filtering, sampling, enrichment, and routing to one or more backends. This decouples applications from backend choice.7374```yaml7576# otel-collector-config.yaml77receivers:78 otlp:79 protocols:80 grpc:81 endpoint: "0.0.0.0:4317"82 http:83 endpoint: "0.0.0.0:4318"8485processors:86 batch:87 timeout: 5s88 send_batch_size: 102489 filter:90 logs:91 exclude:92 match_type: strict93 bodies:94 - "Health check endpoint hit"9596exporters:97 elasticsearch:98 endpoints: ["https://es-cluster:9200"]99 logs_index: "app-logs"100 loki:101 endpoint: "http://loki:3100/loki/api/v1/push"102103service:104 pipelines:105 logs:106 receivers: [otlp]107 processors: [batch, filter]108 exporters: [elasticsearch, loki]109110```text111112**Pattern 2: Direct sink (smaller deployments)**113114```text115116App (Serilog) --> Seq / Elasticsearch sink117118```text119120For smaller systems or development environments, Serilog sinks write directly to the aggregation platform. This avoids the OTel Collector but couples the application to the backend.121122### .NET Application OTLP Configuration123124For .NET application-side OTLP log export configuration (`builder.Logging.AddOpenTelemetry()`), see [skill:dotnet-observability]. The OTLP endpoint is configured via environment variables (`OTEL_EXPORTER_OTLP_ENDPOINT`), keeping application code backend-agnostic.125126---127128## Structured Query Patterns129130Structured logs store each property as a queryable field. The query syntax differs by platform but the concepts are consistent: filter by property name, value, severity, and time range.131132### Kibana KQL (Elasticsearch / ELK)133134```text135136# Find errors for a specific order137level: "Error" AND OrderId: "abc-123"138139# Find slow operations (custom Duration property)140Duration > 5000 AND ServiceName: "order-api"141142# Wildcard on message template143message: "Failed to process*" AND NOT level: "Debug"144145# Time-scoped with correlation146TraceId: "0af7651916cd43dd8448eb211c80319c" AND @timestamp >= "2025-01-15T10:00:00"147148```text149150### Seq Signal Expressions151152```text153154# Find errors for a specific order155@Level = 'Error' and OrderId = 'abc-123'156157# Find slow operations158Duration > 5000 and Application = 'order-api'159160# Free-text search combined with structured filter161@Message like '%timeout%' and @Level in ['Warning', 'Error']162163# Correlation across services164TraceId = '0af7651916cd43dd8448eb211c80319c'165166```text167168Seq signals are saved queries that trigger alerts. Define signals for recurring patterns (e.g., "Payment failures > 10/min") and attach notification channels.169170### Grafana LogQL (Loki)171172```text173174# Filter by labels then regex on log line175{service_name="order-api"} |= "Error" | json | OrderId="abc-123"176177# Structured field extraction and filtering178{service_name="order-api"} | json | Duration > 5000179180# Count errors per service over time (for dashboards)181sum(rate({service_name=~".+"} |= "Error" [5m])) by (service_name)182183```json184185### Azure Monitor KQL (Kusto)186187```kusto188189// Find errors for a specific order190traces191| where severityLevel >= 3192| where customDimensions.OrderId == "abc-123"193| order by timestamp desc194195// Slow operations196traces197| where toint(customDimensions.Duration) > 5000198| where cloud_RoleName == "order-api"199200// Cross-service correlation201union traces, exceptions202| where operation_Id == "0af7651916cd43dd8448eb211c80319c"203| order by timestamp asc204205```text206207---208209## Log Sampling and Volume Management210211High-throughput systems can generate millions of log events per minute. Without sampling, storage costs and query performance degrade rapidly.212213### Sampling Strategies214215| Strategy | How it works | Use when |216|----------|-------------|----------|217| **Head-based** | Decide to sample before processing | Consistent per-request; simple to implement |218| **Tail-based** | Decide to sample after processing | Keep all errors/slow requests, drop routine logs |219| **Level-based** | Sample by severity | Always keep Warning+, sample Debug/Info |220| **Dynamic** | Adjust rate based on volume | Handle traffic spikes without config changes |221222### OTel Collector Log Filtering223224The `filter` processor in the OTel Collector drops log records at the pipeline level before they reach exporters. Use it to exclude noisy low-severity logs and reduce storage volume.225226Note: The `tail_sampling` processor operates on **traces** (spans), not logs. For log volume management, use the `filter` and `transform` processors instead.227228```yaml229230processors:231 filter:232 logs:233 exclude:234 match_type: regexp235 # Drop Debug and Trace logs at the collector level236 severity_texts: ["DEBUG", "TRACE"]237 exclude:238 match_type: strict239 # Exclude health check noise240 bodies:241 - "Health check endpoint hit"242 transform:243 log_statements:244 - context: log245 conditions:246 # Keep all Warning+ logs unconditionally247 - severity_number >= SEVERITY_NUMBER_WARN248 statements: []249250```text251252### Application-Level Sampling with Serilog253254```csharp255256// Serilog.Expressions package for conditional log filtering257builder.Host.UseSerilog((context, loggerConfiguration) =>258{259 loggerConfiguration260 .ReadFrom.Configuration(context.Configuration)261 // Drop health check logs entirely262 .Filter.ByExcluding("RequestPath = '/health/ready'")263 // Sample Debug logs at 10%264 .Filter.ByExcluding(265 "@Level = 'Debug' and Hash(@i) % 10 != 0");266});267268```text269270**Key packages:**271272```xml273274<PackageReference Include="Serilog.Expressions" Version="5.*" />275276```xml277278### Volume Management Checklist2792801. **Set retention policies** per index/stream (e.g., 30 days for Info, 90 days for Error)2812. **Use log level filtering** to suppress noisy framework categories at the source2823. **Exclude health check endpoints** from request logging2834. **Apply index lifecycle management** (ILM in Elasticsearch, retention policies in Loki)2845. **Monitor ingestion rates** and set budget alerts on storage costs285286---287288## PII Scrubbing and Destructuring Policies289290Logs must not contain personally identifiable information (PII) in production. GDPR, HIPAA, and SOC 2 require that sensitive data is masked or excluded from log storage.291292### Property-Level Masking with Enrichers293294```csharp295296// Enricher that masks known-sensitive properties on every log event297public sealed class PiiMaskingEnricher : ILogEventEnricher298{299 private static readonly HashSet<string> s_sensitiveKeys = new(300 StringComparer.OrdinalIgnoreCase)301 {302 "Email", "PhoneNumber", "IpAddress",303 "CreditCard", "SSN", "Password"304 };305306 public void Enrich(LogEvent logEvent, ILogEventPropertyFactory factory)307 {308 var propertiesToMask = logEvent.Properties309 .Where(p => s_sensitiveKeys.Contains(p.Key))310 .Select(p => p.Key)311 .ToList();312313 foreach (var key in propertiesToMask)314 {315 logEvent.AddOrUpdateProperty(316 factory.CreateProperty(key, "***REDACTED***"));317 }318 }319}320321// Registration322loggerConfiguration.Enrich.With<PiiMaskingEnricher>();323324```text325326### OTel Collector Attribute Processing327328```yaml329330processors:331 attributes:332 actions:333 # Mask email addresses using regex334 - key: user.email335 action: update336 value: "***@redacted.com"337 # Remove sensitive attributes entirely338 - key: http.request.header.authorization339 action: delete340 - key: user.password341 action: delete342343```text344345### PII Scrubbing Checklist3463471. **Identify PII fields** -- email, phone, IP, SSN, credit card, auth tokens, cookies3482. **Apply at the earliest point** -- enricher or OTel processor, not at query time3493. **Audit log templates** -- ensure structured log templates do not capture PII as named properties3504. **Test with compliance team** -- validate scrubbing rules against regulatory requirements3515. **Use separate retention** for audit logs that legitimately require PII (with encryption at rest)352353---354355## Cross-Service Correlation356357In distributed systems, a single user request may traverse multiple services. Correlation enables tracing a request across all services and reconstructing the full event timeline.358359### W3C Trace Context Correlation360361The primary correlation mechanism is the W3C `traceparent` header, which propagates automatically through `HttpClient` when OpenTelemetry instrumentation is configured (see [skill:dotnet-observability]). All log events emitted within a traced request include `TraceId` and `SpanId` properties.362363```csharp364365// Query all logs for a distributed operation across services366// In Seq:367TraceId = '0af7651916cd43dd8448eb211c80319c'368369// In Kibana:370TraceId: "0af7651916cd43dd8448eb211c80319c"371372// In Azure Monitor:373traces | where operation_Id == "0af7651916cd43dd8448eb211c80319c"374375```text376377### Custom Correlation IDs378379When trace context is insufficient (e.g., async workflows spanning message queues, batch jobs, or external system callbacks), add custom correlation IDs:380381```csharp382383// Propagate a business correlation ID through Serilog LogContext384public sealed class CorrelationIdMiddleware(RequestDelegate next)385{386 private const string CorrelationHeader = "X-Correlation-Id";387388 public async Task InvokeAsync(HttpContext context)389 {390 var correlationId = context.Request.Headers[CorrelationHeader]391 .FirstOrDefault() ?? Guid.NewGuid().ToString("N");392393 context.Response.Headers[CorrelationHeader] = correlationId;394395 using (LogContext.PushProperty("CorrelationId", correlationId))396 {397 await next(context);398 }399 }400}401402## Detailed Examples403404See [references/detailed-examples.md](references/detailed-examples.md) for complete code samples and advanced patterns.