Monitoring and Logging

1. Logging Request and Response Details

FieldAlways Log
Timestamp (ISO 8601)Yes
Method, path, query (sanitized)Yes
Status codeYes
Duration (ms)Yes
userId / clientIdYes
traceIdYes
Request bodySample / redact PII
Response bodyErrors only by default

2. Using Correlation IDs

Example: Correlation ID Propagation

// Inbound: read or generate
String traceId = req.getHeader("X-Request-ID");
if (traceId == null) traceId = UUID.randomUUID().toString();
MDC.put("traceId", traceId);

// Outbound: forward to downstream services
restTemplate.getForEntity(url, ..., headers -> {
    headers.set("X-Request-ID", MDC.get("traceId"));
});

// Response: echo back
res.setHeader("X-Request-ID", traceId);

3. Monitoring Response Times

MetricTool
p50, p95, p99 latencyPrometheus histogram
Per-endpoint breakdownTag by route
Slowest queriesAPM trace sampling
SLO trackingError budget burn

4. Monitoring Error Rates

BucketTrack Separately
4xx (client errors)Indicates API misuse / bugs
5xx (server errors)Page on threshold
By endpointIdentify hotspots
By dependencyUpstream failure detection

5. Implementing Health Check Endpoints

EndpointPurpose
GET /health/liveProcess is running (200 always when up)
GET /health/readyReady for traffic (DB connected, caches warm)
GET /health/startupInitial bootstrap done (Kubernetes startupProbe)

Example: Readiness Response

{
  "status": "UP",
  "components": {
    "db":    {"status": "UP", "latencyMs": 4},
    "redis": {"status": "UP", "latencyMs": 1},
    "kafka": {"status": "DEGRADED", "message": "1 of 3 brokers down"}
  }
}

6. Monitoring API Usage Patterns

MetricInsight
Requests per endpointMost-used features
Per-client breakdownTop consumers
Geographic distributionCDN / region planning
Time-of-day patternsCapacity planning

7. Using Application Performance Monitoring

ToolStrength
DatadogUnified metrics + traces + logs
New RelicStrong APM, AI insights
HoneycombHigh-cardinality observability
OpenTelemetryOpen standard, vendor-neutral
Grafana + Prometheus + Loki + TempoOpen-source stack

8. Implementing Structured Logging

Example: JSON Log Entry

{
  "timestamp": "2026-05-15T10:30:00.123Z",
  "level": "INFO",
  "logger": "com.example.UserController",
  "message": "User created",
  "traceId": "abc-123",
  "userId": "42",
  "method": "POST",
  "path": "/users",
  "status": 201,
  "durationMs": 87
}

9. Setting Up Alerts

ConditionSeverity
5xx rate > 1% for 5 minPage
p99 latency > SLOWarn
Error budget > 50% burn (7d)Page
Auth failure spikeSecurity alert
Disk > 85%Warn

10. Logging Security Events

EventRequired Fields
Login success/failureuserId, IP, userAgent, timestamp
Permission denieduserId, resource, action
Token issued / revokeduserId, tokenId, source
Admin actionactorId, target, change diff
StorageTamper-evident, retained per compliance

11. Implementing Log Retention Policies

Log TypeRetention
Application (DEBUG/INFO)7-30 days
Access logs30-90 days
Security/audit1-7 years (compliance)
Errors90 days hot, 1 year cold

12. Using Centralized Logging

StackComponents
ELKElasticsearch + Logstash + Kibana
EFKFluentd instead of Logstash
LokiLightweight, label-based
Cloud-nativeCloudWatch, Stackdriver, Azure Monitor