Overview
Logging is not just about writing messages to a file. An effective logging strategy ensures you can debug production issues efficiently without overwhelming your storage.
Key Principles
- Structured Logging: Use JSON format for machine-readability.
- Context Enrichment: Include
trace_id,user_id, andservice_namein every log. - Log Levels: Use them appropriately (DEBUG, INFO, WARN, ERROR, FATAL).
- Log Retention: Implement policies based on business needs and compliance (e.g., GDPR).
Example: Structured Log (JSON)
{
"timestamp": "2026-04-10T10:00:00Z",
"level": "ERROR",
"service": "order-service",
"trace_id": "a1b2c3d4e5f6",
"message": "Database connection failed",
"error_code": "DB_CONN_TIMEOUT"
}Result:
Tools like Loki or Elasticsearch can index these fields, allowing queries like:
service="order-service" | json | error_code="DB_CONN_TIMEOUT"