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

LevelUse
ERRORUnexpected failure; on-call
WARNDegraded; needs attention soon
INFOBusiness events, lifecycle
DEBUGDiagnostic detail
TRACEVery verbose; opt-in

3. Implementing Correlation IDs

SourceHeader
InboundX-Correlation-Id or W3C traceparent
Generate if missingUUID
PropagateTo all downstream calls
Attach to logsVia 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

FieldDetail
timestampUTC, ms precision
actorUser + tenant
actionDomain verb
targetResource type + ID
outcomesuccess / failure
before/afterFor state changes
request idCorrelation

6. Implementing Exception Logging

PracticeDetail
Log onceAt top boundary, not every catch
Include cause chainPass throwable to logger
Don't log + rethrowEither handle or rethrow, not both
Don't log validation errors at ERROR4xx 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

ElementLog?
Method, path, statusAlways
DurationAlways
HeadersSelected (no Authorization)
BodySample / debug only; redact PII
Client IP, user-agentYes

9. Handling Sensitive Data in Logs

FieldTreatment
PasswordNever log
Card numberLast 4 only
EmailMask local part: j***@acme.com
Token/keyHash or first 6 chars
SSN/PIITokenize 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

StackComponents
ELKElasticsearch + Logstash + Kibana
EFKElasticsearch + Fluentd + Kibana
LokiGrafana stack
CloudCloudWatch, Stackdriver, Azure Monitor
SaaSDatadog, Splunk, New Relic

12. Implementing Log Sampling

StrategyDetail
Head sampling1 of N at log call
Tail samplingKeep all if error in trace
AdaptiveIncrease rate on errors
Per-tenantHigher fidelity for premium