Implementing Logging
1. Implementing Structured Logging
Example: SLF4J + JSON
log.info("order placed",
kv("orderId", id),
kv("customerId", customerId),
kv("totalCents", total.cents()));
// → { "level":"INFO", "msg":"order placed", "orderId":"ord_1", ... }
2. Defining Log Levels
| Level | Use |
|---|---|
| ERROR | Unexpected failure; on-call |
| WARN | Degraded; needs attention soon |
| INFO | Business events, lifecycle |
| DEBUG | Diagnostic detail |
| TRACE | Very verbose; opt-in |
3. Implementing Correlation IDs
| Source | Header |
|---|---|
| Inbound | X-Correlation-Id or W3C traceparent |
| Generate if missing | UUID |
| Propagate | To all downstream calls |
| Attach to logs | Via MDC |
4. Using MDC for Context
Example: MDC scoped context
try (var ignored = MDC.putCloseable("orderId", id.toString())) {
process(id); // every log inside includes orderId
}
5. Implementing Audit Logging
| Field | Detail |
|---|---|
| timestamp | UTC, ms precision |
| actor | User + tenant |
| action | Domain verb |
| target | Resource type + ID |
| outcome | success / failure |
| before/after | For state changes |
| request id | Correlation |
6. Implementing Exception Logging
| Practice | Detail |
|---|---|
| Log once | At top boundary, not every catch |
| Include cause chain | Pass throwable to logger |
| Don't log + rethrow | Either handle or rethrow, not both |
| Don't log validation errors at ERROR | 4xx is INFO/WARN |
7. Implementing Performance Logging
Example: Timed operation
@Around("@annotation(Timed)")
public Object timed(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
try { return pjp.proceed(); }
finally {
long ms = (System.nanoTime() - start) / 1_000_000;
meter.timer(pjp.getSignature().toShortString()).record(ms, MILLISECONDS);
}
}
8. Implementing Request/Response Logging
| Element | Log? |
|---|---|
| Method, path, status | Always |
| Duration | Always |
| Headers | Selected (no Authorization) |
| Body | Sample / debug only; redact PII |
| Client IP, user-agent | Yes |
9. Handling Sensitive Data in Logs
| Field | Treatment |
|---|---|
| Password | Never log |
| Card number | Last 4 only |
Mask local part: j***@acme.com | |
| Token/key | Hash or first 6 chars |
| SSN/PII | Tokenize or omit |
10. Implementing Log Rotation Configuration
Example: Logback rolling policy
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>app.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
11. Implementing Log Aggregation
| Stack | Components |
|---|---|
| ELK | Elasticsearch + Logstash + Kibana |
| EFK | Elasticsearch + Fluentd + Kibana |
| Loki | Grafana stack |
| Cloud | CloudWatch, Stackdriver, Azure Monitor |
| SaaS | Datadog, Splunk, New Relic |
12. Implementing Log Sampling
| Strategy | Detail |
|---|---|
| Head sampling | 1 of N at log call |
| Tail sampling | Keep all if error in trace |
| Adaptive | Increase rate on errors |
| Per-tenant | Higher fidelity for premium |