intermediate

Structured logs

Emit machine-readable log events with stable fields for service, environment, request, user-safe context, and outcome.

Structured logs emit machine-readable events—usually JSON—with stable field names instead of free-form strings. That makes filtering, aggregation, and correlation possible in Loki, CloudWatch, Datadog, or ELK without fragile regex.

					logger.info({
  service: 'checkout-api',
  requestId: req.id,
  route: '/orders',
  status: 201,
  durationMs: 42,
  event: 'order_created',
});
				

| Field | Purpose | |-------|---------| | service / env | Scope noise in multi-tenant views | | requestId / traceId | Join logs across hops | | route / operation | Group by user-visible surface | | outcome / status | Drive SLO and error dashboards |

Keep schemas consistent across services. Prefer a small set of required fields plus optional context. Log business outcomes at info when they matter for support—not every debug variable.

On interviews: JSON vs plain text, field naming conventions, cardinality of dynamic keys, and pairing structured logs with correlation IDs.

Common pitfalls: logging entire request bodies; different field names per service; string interpolation that breaks parsing; high-cardinality labels in log indexes.

The trade-off is storage and indexing cost versus query speed during incidents.

Checklist:

  • Use stable field names across services.
  • Include request/trace identifiers.
  • Avoid unbounded dynamic keys.
  • Redact sensitive values before emit.