Implementing Distributed Logging

1. Understanding Structured Logging

Example: JSON structured log

{
  "ts": "2026-05-15T10:23:45.123Z",
  "level": "INFO",
  "service": "order-svc",
  "trace_id": "9f2e1c...",
  "span_id": "a8b3...",
  "user_id": "u-42",
  "event": "order.created",
  "order_id": "o-7",
  "duration_ms": 47
}
FieldPurpose
tsISO 8601 UTC timestamp
levelDEBUG / INFO / WARN / ERROR
service / versionSource identification
trace_id / span_idCorrelate with traces
event / messageMachine + human readable

2. Implementing Correlation IDs (trace IDs)

MechanismDetail
W3C traceparenttraceparent: 00-<trace-id>-<span-id>-01
B3 (Zipkin)X-B3-TraceId, X-B3-SpanId
GenerationEdge gateway creates, propagates downstream
MDC (logback)Per-thread context binding

3. Implementing Log Aggregation

PipelineDetail
CollectFluent Bit, Vector, Filebeat, Promtail
TransportKafka, Kinesis
Index / storeElasticsearch/OpenSearch, Loki, Splunk
QueryKibana, Grafana, Splunk SPL

4. Implementing Centralized Logging

StackComponents
ELK / OpenSearchLogstash → ES → Kibana
Loki + Promtail + GrafanaLower cost, label-based
SplunkEnterprise, broad indexing
Datadog / New RelicManaged SaaS

5. Understanding Log Levels

LevelUse
TRACEVerbose, dev only
DEBUGDiagnostic; off in prod usually
INFOSignificant business events
WARNRecoverable issue, attention soon
ERRORAction failed; needs investigation
FATALProcess unable to continue

6. Implementing Log Sampling

StrategyDetail
Head samplingDecide at request entry
Tail samplingDecide after observing whole trace; keep errors
Rate-limitedN per second per logger
AdaptiveSample less when traffic high

7. Implementing Log Retention Policies

TierRetentionStorage
Hot (search)7-30 daysSSD ES/OpenSearch
Warm30-90 daysHDD nodes
Cold / archive1-7 yearsS3 Glacier, IA
CompliancePer regulation (SOX 7yr, GDPR varies)

8. Handling Log Shipping and Buffering

ConcernMitigation
Backpressure on appAsync appender + bounded queue
Loss on crashLocal file buffer + retry
Network partitionPersistent on-disk queue (Vector)
SpikesKafka buffer, downstream rate limit

9. Implementing Log Parsing and Indexing

ApproachDetail
Native JSONNo parsing; ES indexes fields
Grok patternsRegex extraction (Logstash)
VRL (Vector)Programmatic transforms
Cardinality controlAvoid high-cardinality labels in Loki/Prom

10. Understanding Logging Best Practices

PracticeDetail
Structured (JSON)Machine parseable
Include trace idsCross-reference with traces
No PII / secretsMask, redact, or reject
Use levels correctlyAvoid INFO-spam
Async appenderDon't block request thread
UTC timestampsTimezone-free