SteelReed

Search

Search posts, questions…

6. DevOps & Operations

Logging for backends: log levels, structured logs, MDC and a centralized log pipeline with ELK or Loki

What to log at which level, turning on the JSON logging built into Spring Boot 3.4+ (ECS, Logstash, GELF), carrying traceId through MDC and thread pools, never leaking passwords or tokens, shipping logs via stdout → Fluent Bit → Elasticsearch/Kibana or Loki, or OTLP, with how to estimate volume and how to review logging config written by AI.

19 Nov 20267 min readMid

–

1. The problem

2 a.m., 5% of payments fail. Logs are free text spread across 30 pods, with no orderId or traceId; grepping each pod takes 40 minutes. Last week someone turned on DEBUG: 1.24 TB of logs a day, and the Elasticsearch cluster filled its disks before the app fell over.

2. Key idea

Logs are a flight recorder: enough to reconstruct what happened, not every noise. Metrics answer "is something wrong", traces answer "which hop is slow", logs answer "what happened to this request". A good log line has context: payment failed orderId=98765 provider=vnpay code=24, not Payment failed.

2.1 Which level?

Level When Example
ERROR couldn't do the job, a human must look DB lost after retries, a 500
WARN abnormal, handled automatically second retry succeeded
INFO business and lifecycle events payment succeeded
DEBUG investigation, off by default outbound call parameters

Validation errors, 404s and wrong passwords are normal client behaviour: INFO or not logged. Log each exception once, where the decision to handle it is made (usually @RestControllerAdvice). Lower layers add context and rethrow; logging and rethrowing at every layer turns one error into three stack traces.

2.2 Where do logs go?

The app writes only to stdout. A DaemonSet agent (Fluent Bit, Vector, OTel Collector) reads files on the node, adds Kubernetes metadata and ships them. The app doesn't depend on the log system, and logs survive pod deletion.

Store Use when Don't use when
Elasticsearch/OpenSearch full-text search, aggregations, security analysis little disk/RAM, nobody to run a cluster
Loki + Grafana high-volume ops logs; indexes only labels, cheap frequent content search over wide time ranges
Cloud (CloudWatch, Cloud Logging) you don't want to run it high volume, ingest fees too high

Loki can't handle high-cardinality labels (userId, traceId): keep them in the content.

3. In Java

PROPERTIES
# application-prod.properties (Spring Boot 3.4+ and 4.x); keep text logs locally
logging.structured.format.console=ecs        # or logstash, gelf
logging.structured.ecs.service.name=order-service
logging.structured.ecs.service.environment=prod
JAVA
log.atInfo()
   .addKeyValue("orderId", order.id())        // its own JSON field, filterable as orderId:98765
   .addKeyValue("provider", r.provider())
   .log("payment succeeded");
// {"@timestamp":"...","log.level":"INFO","message":"payment succeeded","orderId":98765,
//  "provider":"vnpay","traceId":"4bf92f35...","spanId":"00f067aa...","service.name":"order-service"}

Micrometer Tracing puts traceId and spanId into the MDC (a map bound to the current thread), so they appear on every line. With your own logback-spring.xml you must use StructuredLogEncoder, or the properties above do nothing. Other languages: Go log/slog with JSONHandler; Node.js pino; Python structlog.

MDC across thread pools and sensitive data

MDC is a ThreadLocal. @Async, CompletableFuture and hand-made executors all lose it. Use a TaskDecorator (capture MDC.getCopyOfContextMap() on the calling thread, set it in the task, restore in finally) or context propagation. Across Kafka, the trace id travels in a header. Forget MDC.clear() and the next pooled thread carries a stale id.

Never log: passwords, access/refresh tokens, Authorization, Cookie, OTPs, full card numbers, CVVs, national ID numbers. Mask in the app, don't wait for Logstash: once data leaves the process it's in a file on the node and in Kafka buffers. log.info("Updated {}", user) with Lombok's @Data prints the password hash; log the id and chosen fields, use @ToString.Exclude.

Operations: Logback's AsyncAppender has a 256-event queue by default and drops INFO and below when nearly full. addKeyValue keys taken from user input grow the field count without bound; Elasticsearch rejects past 1,000 fields per index by default.

4. Working with AI

Delegate to AI: profile-based logback-spring.xml, an access-log filter, a masking function with tests, Kibana/LogQL queries.

Check yourself:

  • Boot 3.4+ uses the built-in logging.structured.format.*; adding logstash-logback-encoder needs a reason.
  • No logging of Authorization, Cookie, login or payment bodies.
  • Every MDC.put has an MDC.clear() or restore in finally.
  • No log.error(...) followed by throw e in lower layers.
  • The prod profile doesn't enable DEBUG for root or the app's packages.

5. Exercises

Exercise 1: Review a "safe, masked" log filter

Find at least three bugs.

JAVA
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
        throws ServletException, IOException {
    MDC.put("userId", req.getHeader("X-User-Id"));
    var wrapped = new ContentCachingRequestWrapper(req);
    chain.doFilter(wrapped, res);
    String body = new String(wrapped.getContentAsByteArray(), UTF_8);
    log.info("{} {} auth={} body={}", req.getMethod(), req.getRequestURI(),
             req.getHeader("Authorization"), LogMasker.mask(body));
}
Solution to Exercise 1
  • MDC.put without MDC.clear() in finally: the next pooled thread carries the wrong userId, even when an exception is thrown.
  • The Authorization header is printed raw; LogMasker isn't applied to it. Drop it entirely, don't mask it.
  • Bodies are logged for every endpoint, unbounded: login, payment and uploads go straight into logs. Log metadata only; if you truly need bodies, truncate to a few KB and keep an exclusion list.
  • Missing status and durationMs; use addKeyValue so they become JSON fields.
  • Test: call /login with Authorization: Bearer x, capture logs with OutputCaptureExtension, assert Bearer x and the password don't appear.

Exercise 2: Read the log-cluster incident

Elasticsearch disks at 92%. 40 pods, 150 requests/s each, 4 log lines per request, 600 bytes per line; 1 replica, 14-day retention. Estimate the volume, act within 15 minutes, fix the root cause.

Solution to Exercise 2
  • 40 × 150 × 4 = 24,000 lines/s × 600 bytes = 14.4 MB/s ≈ 1.24 TB/day. Rough estimate: stored ≈ raw, ×2 for the replica, 14 days ≈ 35 TB.
  • 15 minutes: aggregate by service.name and log.level to find the noisiest service; lower its level via /actuator/loggers; delete the oldest indices early.
  • Root fix: 1 INFO line per request → ~8.7 TB for 14 days, 4x less from log discipline alone. DEBUG off by default; keep error logs longer than INFO; drop health-check access logs.

Summary

  • Pick levels by "who reads it, and when"; client errors aren't ERROR.
  • Log each exception once, where it's handled.
  • JSON logs with traceId; Boot 3.4+ enables them with logging.structured.format.console.
  • MDC is a ThreadLocal: carry it across pools, clear it in finally.
  • Never log secrets; mask in the app; the app writes only to stdout.

Further reading: Observability for LLM calls.


Self-compiled notes from official documentation and hands-on practice.

Practice interview questions on this topic

All DevOps & Cloud questions →

Loading comments…
Next on the roadmapSpring Boot Actuator: health, metrics and production monitoring