Imagine investigating a five-minute latency spike on a small order-API service. The log file contains forty thousand lines reading starting validation, validation passed, and fetching account, interleaved across concurrent requests without shared identifiers. Meanwhile, the three questions that matter—which route stalled, whether the time went to database locks or an upstream call, and how many callers saw an error—cannot be answered from the file.
This is an illustrative scenario, not an incident report from a real deployment. Logs become hard to use when they are written as step-by-step narration for the author who just wrote a function rather than as diagnostic evidence for the maintainer reading at two in the morning.
Emit one summary record per unit of work
Scattershot log statements inside helper functions split one request’s story across a dozen lines. Under concurrency those lines interleave; under partial failure the final line never prints; under normal traffic nine out of ten lines repeat static strings that add storage cost without adding information.
Instead, attach a mutable context struct to each HTTP request, background job, or CLI transaction. As execution proceeds, accumulate counters, dependency timings, retry counts, and outcome codes on that context, then emit a single structured record in a finally block when the unit of work finishes.
- Identity
- Timestamp, service version, request or job ID, and route template (never raw high-cardinality paths with embedded tokens).
- Outcome
- Final status code or result enum, error classification if failed, and whether a retry can safely proceed.
- Timing
- Total wall-clock duration alongside the time spent waiting on storage or external dependencies.
- Work counters
- Rows touched, bytes transferred, cache hit state, or retry attempt number.
Ten lines saying “entered step N” are harder to query and easier to lose than one completion record carrying the outcome and timings of all ten steps.
Carry one correlation identity across boundaries
When a single operation crosses a reverse proxy, an application process, and a background queue, local process logs are useful only if they can be joined without timestamp guesswork. Clock skew of even fifty milliseconds is enough to scramble ordering on a busy host.
Assign or validate a request identifier at the outer ingress boundary, pass it forward to downstream calls and queued tasks, and echo a safe opaque identifier in error responses so a caller report maps straight to the server record. Standards such as the W3C Trace Context specification define a compact traceparent header format for propagating trace and parent-span identifiers across HTTP intermediaries without vendor lock-in.
Keep secrets out by allowlist, not regex cleanup
Dumping full request headers, query strings, environment maps, or raw exception payloads eventually writes bearer tokens, session cookies, signed URLs, or private addresses into persistent logs and backups. Post-hoc regular expressions always lag behind the next credential format.
Log an explicit allowlist of safe scalar fields—status codes, route names, byte counts, durations, and sanitized error categories. Treat URLs with query parameters and raw upstream payloads as sensitive by default: if a WebSocket or webhook URL carries an authentication token, even a reverse-proxy error log configured at too verbose a level can leak that credential on a transient upstream reset. Keep the diagnostic boundary aligned with keeping small systems legible: record what happened without turning logs into a second secret store.
Bound volume when a dependency fails
The moment logs matter most—during a network partition, a full disk, or a tight reconnect loop—is also the moment naive logging does the most damage. Writing megabytes of identical stack traces per second can saturate disk IOPS, rotate away the initial root-cause entries right before the outage began, or block threads on synchronous standard-error writes.
Put explicit caps at both the application and host layers. In the application, sample or aggregate repeated identical transport errors over a short window (logging the first occurrence plus a suppressed count when the window closes). At the host layer, journald.conf provides RateLimitIntervalSec=, RateLimitBurst=, and SystemMaxUse= so a runaway service cannot consume the root filesystem, complemented by tested rotation rules on any standalone files.
Tie every recurring log field to a decision
Before adding a new log statement, name the question it answers during maintenance or incident response. Good log fields pair directly with the operational checks elsewhere in the system: a configuration reload logs the candidate identifier and generation discussed in verify the configuration a service loaded; a retry loop logs the attempt count and state check required by a timeout leaves the outcome unknown; an error record names the condition that triggers an alert with a next action.
If a line never helps confirm a deployment, diagnose a degraded dependency, or verify a security boundary—and fires thousands of times an hour—delete it or fold its counter into the unit-of-work summary.
A small-service logging checklist
- One wide event per transaction: emit a single completion record in a
finallypath with status, total duration, and dependency wait time. - Propagate correlation IDs: carry one request or job identifier across proxy, worker, and error response.
- Allowlist logged fields: never serialize raw headers, query strings, credentials, or unvalidated user payloads.
- Cap failure-loop volume: rate-limit repeated errors in code and enforce journald or logrotate disk ceilings on the host.
- Verify under fault injection: trigger one controlled timeout and one rejected request, then confirm the resulting two lines answer what failed, where, and what to do next.
Quiet during healthy hours and specific when something breaks is the right shape for a small system’s logs: fewer lines, richer context, and zero leaked secrets.