Logging & Observability
Patterns for building observable systems across the three pillars: logs, metrics, and traces.
Three Pillars
| Pillar |
Purpose |
Question It Answers |
Example |
| Logs |
What happened |
Why did this request fail? |
{"level":"error","msg":"payment declined","user_id":"u_82"} |
| Metrics |
How much / how fast |
Is latency increasing? |
http_request_duration_seconds{route="/api/orders"} 0.342 |
| Traces |
Request flow |
Where is the bottleneck? |
Span: api-gateway → auth → order-service → db |
Each pillar is strongest when correlated. Embed trace_id in every log line to jump from a log entry to the full distributed trace.
Structured Logging
Always emit logs as structured JSON — never free-text strings.
Required Fields
| Field |
Purpose |
Required |
timestamp |
ISO-8601 with milliseconds |
Yes |
level |
Severity (DEBUG … FATAL) |
Yes |
service |
Originating service name |
Yes |
message |
Human-readable description |
Yes |
trace_id |
Distributed trace correlation |
Yes |
span_id |
Current span within trace |
Yes |
correlation_id |
Business-level correlation (order ID) |
When applicable |
error |
Structured error object |
On errors |
context |
Request-specific metadata |
Recommended |
Context Enrichment
Attach context at the middleware level so downstream logs inherit automatically:
app.use((req, res, next) => {
const ctx = {
trace_id: req.headers['x-trace-id'] || crypto.randomUUID(),
request_id: crypto.randomUUID(),
user_id: req.user?.id,
method: req.method,
path: req.path,
};
asyncLocalStorage.run(ctx, () => next());
});
Library Recommendations
| Library |
Language |
Strengths |
Perf |
| Pino |
Node.js |
Fastest Node logger, low overhead |
Excellent |
| structlog |
Python |
Composable processors, context binding |
Good |
| zerolog |
Go |
Zero-allocation JSON logging |
Excellent |
| zap |
Go |
High performance, typed fields |
Excellent |
| tracing |
Rust |
Spans + events, async-aware |
Excellent |
Choose a logger that outputs structured JSON natively. Avoid loggers requiring post-processing.
Log Levels
| Level |
When to Use |
Example |
| FATAL |
App cannot continue, process will exit |
Database connection pool exhausted |
| ERROR |
Operation failed, needs attention |
Payment charge failed: CARD_DECLINED |
| WARN |
Unexpected but recoverable |
Retry 2/3 for upstream timeout |
| INFO |
Normal business events |
Order ORD-1234 placed successfully |
| DEBUG |
Developer troubleshooting |
Cache miss for key user:82:preferences |
| TRACE |
Very fine-grained (rarely in prod) |
Entering validateAddress with payload |
Rules: Production default = INFO and above. If you log an ERROR, someone should act on it. Every FATAL should trigger an alert.
Distributed Tracing
OpenTelemetry Setup
Always prefer OpenTelemetry over vendor-specific SDKs:
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
const sdk = new NodeSDK({
serviceName: 'order-service',
traceExporter: new OTLPTraceExporter({
url: 'http://otel-collector:4318/v1/traces',
}),
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
Span Creation
const tracer = trace.getTracer('order-service');
async function processOrder(order: Order) {
return tracer.startActiveSpan('processOrder', async (span) => {
try {
span.setAttribute('order.id', order.id);
span.setAttribute('order.total_cents', order.totalCents);
await validateInventory(order);
await chargePayment(order);
span.setStatus({ code: SpanStatusCode.OK });
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
span.recordException(err);
throw err;
} finally {
span.end();
}
});
}
Context Propagation
- Use W3C Trace Context (
traceparent header) — default in OTel
- Propagate across HTTP, gRPC, and message queues
- For async workers: serialise
traceparent into the job payload
Trace Sampling
| Strategy |
Use When |
| Always On |
Low-traffic services, debugging |
| Probabilistic (N%) |
General production use |
| Rate-limited (N/sec) |
High-throughput services |
| Tail-based |
When you need all error traces |
Always sample 100% of error traces regardless of strategy.
Metrics Collection
RED Method (Request-Driven)
Monitor these three for every service endpoint:
| Metric |
What It Measures |
Prometheus Example |
| Rate |
Requests/sec |
rate(http_requests_total[5m]) |
| Errors |
Failed request ratio |
rate(http_requests_total{status=~"5.."}[5m]) |
| Duration |
Response time |
histogram_quantile(0.99, http_request_duration_seconds) |
USE Method (Resource-Driven)
For infrastructure components (CPU, memory, disk, network):
| Metric |
What It Measures |
Example |
| Utilization |
% resource busy |
CPU usage at 78% |
| Saturation |
Work queued/waiting |
12 requests queued in thread pool |
| Errors |
Error events on resource |
3 disk I/O errors in last minute |
Monitoring Stack
| Tool |
Category |
Best For |
| Prometheus |
Metrics |
Pull-based metrics, alerting rules |
| Grafana |
Visualisation |
Dashboards for metrics, logs, traces |
| Jaeger |
Tracing |
Distributed trace visualisation |
| Loki |
Logs |
Log aggregation (pairs with Grafana) |
| OpenTelemetry |
Collection |
Vendor-neutral telemetry collection |
Recommendation: Start with OTel Collector → Prometheus + Grafana + Loki + Jaeger. Migrate to SaaS only when operational overhead justifies cost.
Alert Design
Severity Levels
| Severity |
Response Time |
Example |
| P1 |
Immediate |
Service fully down, data loss |
| P2 |
< 30 min |
Error rate > 5%, latency p99 > 5s |
| P3 |
Business hours |
Disk > 80%, cert expiring in 7 days |
| P4 |
Best effort |
Non-critical deprecation warning |
Alert Fatigue Prevention
- Alert on symptoms, not causes — "error rate > 5%" not "pod restarted"
- Multi-window, multi-burn-rate — catch both sudden spikes and slow burns
- Require runbook links — every alert must link to diagnosis and remediation
- Review monthly — delete or tune alerts that never fire or always fire
- Group related alerts — use inhibition rules to suppress child alerts
- Set appropriate thresholds — if alert fires daily and is ignored, raise threshold or delete
Dashboard Patterns
Overview Dashboard ("War Room")
- Total requests/sec across all services
- Global error rate (%) with trendline
- p50 / p95 / p99 latency
- Active alerts count by severity
- Deployment markers overlaid on graphs
Service Dashboard (Per-Service)
- RED metrics for each endpoint
- Dependency health (upstream/downstream success rates)
- Resource utilisation (CPU, memory, connections)
- Top errors table with count and last seen
Observability Checklist
Every service must have:
Anti-Patterns
| Anti-Pattern |
Problem |
Fix |
| Logging PII |
Privacy/compliance violation |
Mask or exclude PII; use token references |
| Excessive logging |
Storage costs balloon, signal drowns |
Log business events, not data flow |
| Unstructured logs |
Cannot query or alert on fields |
Use structured JSON with consistent schema |
| String interpolation |
Breaks structured fields, injection risk |
Pass fields as metadata, not in message |
| Missing correlation IDs |
Cannot trace across services |
Generate and propagate trace_id everywhere |
| Alert storms |
On-call fatigue, real issues buried |
Use grouping, inhibition, deduplication |
| Metrics with high cardinality |
Prometheus OOM, dashboard timeouts |
Never use user ID or request ID as label |
NEVER Do
- NEVER log passwords, tokens, API keys, or secrets — even at DEBUG level
- NEVER use console.log / print in production — use a structured logger
- NEVER use user IDs, emails, or request IDs as metric labels — cardinality will explode
- NEVER create alerts without a runbook link — unactionable alerts erode trust
- NEVER rely on logs alone — you need metrics and traces for full observability
- NEVER log request/response bodies by default — opt-in only, with PII redaction
- NEVER ignore log volume — set budgets and alert when a service exceeds daily quota
- NEVER skip context propagation in async flows — broken traces are worse than no traces
1---
2name: logging-observability
3model: standard
4description: Structured logging, distributed tracing, and metrics collection patterns for building observable systems. Use when implementing logging infrastructure, setting up distributed tracing with OpenTelemetry, designing metrics collection (RED/USE methods), configuring alerting and dashboards, or reviewing observability practices. Covers structured JSON logging, context propagation, trace sampling, Prometheus/Grafana stack, alert design, and PII/secret scrubbing.
5version: 1.0.0
6metadata:
7 source: https://skillmd.com/skills/modbender/logging-observability
8---
9
10# Logging & Observability
11
12Patterns for building observable systems across the three pillars: logs, metrics, and traces.
13
14## Three Pillars
15
16| Pillar | Purpose | Question It Answers | Example |
17|--------|---------|---------------------|---------|
18| **Logs** | What happened | Why did this request fail? | `{"level":"error","msg":"payment declined","user_id":"u_82"}` |
19| **Metrics** | How much / how fast | Is latency increasing? | `http_request_duration_seconds{route="/api/orders"} 0.342` |
20| **Traces** | Request flow | Where is the bottleneck? | Span: `api-gateway → auth → order-service → db` |
21
22Each pillar is strongest when correlated. Embed `trace_id` in every log line to jump from a log entry to the full distributed trace.
23
24---
25
26## Structured Logging
27
28Always emit logs as structured JSON — never free-text strings.
29
30### Required Fields
31
32| Field | Purpose | Required |
33|-------|---------|----------|
34| `timestamp` | ISO-8601 with milliseconds | Yes |
35| `level` | Severity (DEBUG … FATAL) | Yes |
36| `service` | Originating service name | Yes |
37| `message` | Human-readable description | Yes |
38| `trace_id` | Distributed trace correlation | Yes |
39| `span_id` | Current span within trace | Yes |
40| `correlation_id` | Business-level correlation (order ID) | When applicable |
41| `error` | Structured error object | On errors |
42| `context` | Request-specific metadata | Recommended |
43
44### Context Enrichment
45
46Attach context at the middleware level so downstream logs inherit automatically:
47
48```typescript
49app.use((req, res, next) => {
50 const ctx = {
51 trace_id: req.headers['x-trace-id'] || crypto.randomUUID(),
52 request_id: crypto.randomUUID(),
53 user_id: req.user?.id,
54 method: req.method,
55 path: req.path,
56 };
57 asyncLocalStorage.run(ctx, () => next());
58});
59```
60
61### Library Recommendations
62
63| Library | Language | Strengths | Perf |
64|---------|----------|-----------|------|
65| **Pino** | Node.js | Fastest Node logger, low overhead | Excellent |
66| **structlog** | Python | Composable processors, context binding | Good |
67| **zerolog** | Go | Zero-allocation JSON logging | Excellent |
68| **zap** | Go | High performance, typed fields | Excellent |
69| **tracing** | Rust | Spans + events, async-aware | Excellent |
70
71Choose a logger that outputs structured JSON natively. Avoid loggers requiring post-processing.
72
73---
74
75## Log Levels
76
77| Level | When to Use | Example |
78|-------|-------------|---------|
79| **FATAL** | App cannot continue, process will exit | Database connection pool exhausted |
80| **ERROR** | Operation failed, needs attention | Payment charge failed: CARD_DECLINED |
81| **WARN** | Unexpected but recoverable | Retry 2/3 for upstream timeout |
82| **INFO** | Normal business events | Order ORD-1234 placed successfully |
83| **DEBUG** | Developer troubleshooting | Cache miss for key user:82:preferences |
84| **TRACE** | Very fine-grained (rarely in prod) | Entering validateAddress with payload |
85
86**Rules:** Production default = INFO and above. If you log an ERROR, someone should act on it. Every FATAL should trigger an alert.
87
88---
89
90## Distributed Tracing
91
92### OpenTelemetry Setup
93
94Always prefer OpenTelemetry over vendor-specific SDKs:
95
96```typescript
97import { NodeSDK } from '@opentelemetry/sdk-node';
98import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
99import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
100
101const sdk = new NodeSDK({
102 serviceName: 'order-service',
103 traceExporter: new OTLPTraceExporter({
104 url: 'http://otel-collector:4318/v1/traces',
105 }),
106 instrumentations: [getNodeAutoInstrumentations()],
107});
108sdk.start();
109```
110
111### Span Creation
112
113```typescript
114const tracer = trace.getTracer('order-service');
115
116async function processOrder(order: Order) {
117 return tracer.startActiveSpan('processOrder', async (span) => {
118 try {
119 span.setAttribute('order.id', order.id);
120 span.setAttribute('order.total_cents', order.totalCents);
121 await validateInventory(order);
122 await chargePayment(order);
123 span.setStatus({ code: SpanStatusCode.OK });
124 } catch (err) {
125 span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
126 span.recordException(err);
127 throw err;
128 } finally {
129 span.end();
130 }
131 });
132}
133```
134
135### Context Propagation
136
137- Use W3C Trace Context (`traceparent` header) — default in OTel
138- Propagate across HTTP, gRPC, and message queues
139- For async workers: serialise `traceparent` into the job payload
140
141### Trace Sampling
142
143| Strategy | Use When |
144|----------|----------|
145| **Always On** | Low-traffic services, debugging |
146| **Probabilistic** (N%) | General production use |
147| **Rate-limited** (N/sec) | High-throughput services |
148| **Tail-based** | When you need all error traces |
149
150Always sample 100% of error traces regardless of strategy.
151
152---
153
154## Metrics Collection
155
156### RED Method (Request-Driven)
157
158Monitor these three for every service endpoint:
159
160| Metric | What It Measures | Prometheus Example |
161|--------|-----------------|-------------------|
162| **Rate** | Requests/sec | `rate(http_requests_total[5m])` |
163| **Errors** | Failed request ratio | `rate(http_requests_total{status=~"5.."}[5m])` |
164| **Duration** | Response time | `histogram_quantile(0.99, http_request_duration_seconds)` |
165
166### USE Method (Resource-Driven)
167
168For infrastructure components (CPU, memory, disk, network):
169
170| Metric | What It Measures | Example |
171|--------|-----------------|---------|
172| **Utilization** | % resource busy | CPU usage at 78% |
173| **Saturation** | Work queued/waiting | 12 requests queued in thread pool |
174| **Errors** | Error events on resource | 3 disk I/O errors in last minute |
175
176---
177
178## Monitoring Stack
179
180| Tool | Category | Best For |
181|------|----------|----------|
182| **Prometheus** | Metrics | Pull-based metrics, alerting rules |
183| **Grafana** | Visualisation | Dashboards for metrics, logs, traces |
184| **Jaeger** | Tracing | Distributed trace visualisation |
185| **Loki** | Logs | Log aggregation (pairs with Grafana) |
186| **OpenTelemetry** | Collection | Vendor-neutral telemetry collection |
187
188**Recommendation:** Start with OTel Collector → Prometheus + Grafana + Loki + Jaeger. Migrate to SaaS only when operational overhead justifies cost.
189
190---
191
192## Alert Design
193
194### Severity Levels
195
196| Severity | Response Time | Example |
197|----------|---------------|---------|
198| **P1** | Immediate | Service fully down, data loss |
199| **P2** | < 30 min | Error rate > 5%, latency p99 > 5s |
200| **P3** | Business hours | Disk > 80%, cert expiring in 7 days |
201| **P4** | Best effort | Non-critical deprecation warning |
202
203### Alert Fatigue Prevention
204
205- **Alert on symptoms, not causes** — "error rate > 5%" not "pod restarted"
206- **Multi-window, multi-burn-rate** — catch both sudden spikes and slow burns
207- **Require runbook links** — every alert must link to diagnosis and remediation
208- **Review monthly** — delete or tune alerts that never fire or always fire
209- **Group related alerts** — use inhibition rules to suppress child alerts
210- **Set appropriate thresholds** — if alert fires daily and is ignored, raise threshold or delete
211
212---
213
214## Dashboard Patterns
215
216### Overview Dashboard ("War Room")
217- Total requests/sec across all services
218- Global error rate (%) with trendline
219- p50 / p95 / p99 latency
220- Active alerts count by severity
221- Deployment markers overlaid on graphs
222
223### Service Dashboard (Per-Service)
224- RED metrics for each endpoint
225- Dependency health (upstream/downstream success rates)
226- Resource utilisation (CPU, memory, connections)
227- Top errors table with count and last seen
228
229---
230
231## Observability Checklist
232
233Every service must have:
234
235- [ ] Structured JSON logging with consistent schema
236- [ ] Correlation / trace IDs propagated on all requests
237- [ ] RED metrics exposed for every external endpoint
238- [ ] Health check endpoints (`/healthz` and `/readyz`)
239- [ ] Distributed tracing with OpenTelemetry
240- [ ] Dashboards for RED metrics and resource utilisation
241- [ ] Alerts for error rate, latency, and saturation with runbook links
242- [ ] Log level configurable at runtime without redeployment
243- [ ] PII scrubbing verified and tested
244- [ ] Retention policies defined for logs, metrics, and traces
245
246## Anti-Patterns
247
248| Anti-Pattern | Problem | Fix |
249|-------------|---------|-----|
250| Logging PII | Privacy/compliance violation | Mask or exclude PII; use token references |
251| Excessive logging | Storage costs balloon, signal drowns | Log business events, not data flow |
252| Unstructured logs | Cannot query or alert on fields | Use structured JSON with consistent schema |
253| String interpolation | Breaks structured fields, injection risk | Pass fields as metadata, not in message |
254| Missing correlation IDs | Cannot trace across services | Generate and propagate trace_id everywhere |
255| Alert storms | On-call fatigue, real issues buried | Use grouping, inhibition, deduplication |
256| Metrics with high cardinality | Prometheus OOM, dashboard timeouts | Never use user ID or request ID as label |
257
258## NEVER Do
259
2601. **NEVER log passwords, tokens, API keys, or secrets** — even at DEBUG level
2612. **NEVER use console.log / print in production** — use a structured logger
2623. **NEVER use user IDs, emails, or request IDs as metric labels** — cardinality will explode
2634. **NEVER create alerts without a runbook link** — unactionable alerts erode trust
2645. **NEVER rely on logs alone** — you need metrics and traces for full observability
2656. **NEVER log request/response bodies by default** — opt-in only, with PII redaction
2667. **NEVER ignore log volume** — set budgets and alert when a service exceeds daily quota
2678. **NEVER skip context propagation in async flows** — broken traces are worse than no traces