Implement structured logging with context propagation: correlation IDs, redaction,…
- User
Implement structured logging with context propagation: correlation IDs, redaction, sampling, and retention policy.
- Assistant
Implement structured logging with context propagation: correlation IDs, redaction, sampling, and retention policy.
Designing structured logging
The user wants to implement structured logging with context propagation. They haven't specified a language or framework, but I can propose a generic approach that's applicable across various environments like Node.js, Python, Go, and Java. It might be helpful to ask for clarification about their preferred stack, but I could also deliver a language-agnostic architecture with pseudocode. Key elements should include correlation IDs, redaction of PII, sampling policies, and retention strategies. I need to focus on providing a comprehensive, yet minimal, answer that covers all these aspects.Creating a reference implementation
I see the user is looking for a reference implementation for structured logging, potentially in languages like Python, Node.js, or Go. While I could deliver detailed code snippets, it might be better to keep it concise and focus on a specific language, like Node.js. It's important to outline generic steps that apply to multiple languages. I’ll include a log schema, context propagation strategies, redaction techniques, and sampling guidelines. This structured approach will help ensure clarity and comprehensiveness.Structuring logging implementation
I’m outlining a plan for structured logging focused on sampling, retention, and observability integration. I suggest a per-request sampling strategy based on the hash of the correlation ID, with customizable sampling ratios included in logs. For retention, I recommend rotating logs and utilizing centralized storage settings for different log levels. I plan to provide integration examples and unit tests, focusing on a single stack, like Node.js with pino. This will include context handling and configuration for redaction and sampling. Let's keep it clear and organized!Implementing structured logging
I need to create a logging solution that utilizes context management features like AsyncLocalStorage in Node.js, contextvars in Python, and context.Context in Go. I’ll implement a getLogger() function that handles request-scoped logs and includes relevant context fields. For outbound requests, I will wrap fetch calls to attach necessary headers and configure built-in redaction for sensitive paths while also implementing a stable sampling function for non-error logs. Lastly, I'll document retention policy examples for Elasticsearch and S3, providing a markdown answer with both language-agnostic details and specific Node.js examples.
Adopt a single JSON schema so logs are queryable and correlate across services.
Recommended base fields
ts (ISO8601 or epoch ms)level (debug|info|warn|error)msgservice, env, versioncorrelation_id (your cross-service “thread”)trace_id, span_id (if you have distributed tracing; use W3C traceparent)request_id (unique per hop/service)method, path, status, duration_msremote_ip (often truncated/anonymized)user_id_hash (hash, not raw), tenant_iderr.type, err.message, err.stacksampled (bool), sample_rate (e.g., 0.1)log_class (e.g., app|access|audit|security)Rules
Header convention
traceparent (W3C).x-correlation-id (or x-request-id).Implement deny-list redaction on known sensitive keys and guardrails:
password, pass, secret, token, apiKey, authorization, cookie, set-cookie, ssn, email, phone, creditCard, etc.Important: redact before serialization and before shipping to log aggregation.
Use deterministic sampling per request so a given correlation_id is either fully kept or mostly dropped for lower-value logs.
Typical policy:
error/warn: 100% keepinfo: keep 10% (or based on endpoint)debug: keep 0–1% (usually off in prod)Deterministic decision:
keep = hash(correlation_id) % 100 < (sample_rate*100)sampled=true/false + sample_rate when emitted.Retention is almost always enforced in your log backend (Elastic/Opensearch, Loki, CloudWatch, Datadog, Splunk, S3), not in app code.
Example policy (adjust for compliance):
security / audit: 365 dayserror: 90 daysaccess / app info: 30 daysdebug/trace: 7 daysImplementation patterns:
pino + AsyncLocalStorage)This shows: structured JSON, context propagation, redaction, deterministic sampling, and outbound header injection.
logger.jsimport pino from "pino";
import crypto from "crypto";
import { AsyncLocalStorage } from "node:async_hooks";
export const als = new AsyncLocalStorage();
function stableSample(correlationId, rate) {
if (!rate || rate >= 1) return true;
const h = crypto.createHash("sha1").update(String(correlationId)).digest();
const n = h.readUInt32BE(0) / 0xffffffff; // 0..1
return n < rate;
}
function correlationFromHeaders(req) {
return (
req.headers["x-correlation-id"] ||
req.headers["x-request-id"] ||
null
);
}
function newId() {
return crypto.randomUUID();
}
// Pino instance with redaction
export const baseLogger = pino({
level: process.env.LOG_LEVEL || "info",
redact: {
paths: [
"req.headers.authorization",
"req.headers.cookie",
"req.headers['set-cookie']",
"req.body.password",
"req.body.token",
"req.body.secret",
"*.password",
"*.token",
"*.secret",
"*.apiKey",
],
censor: "[REDACTED]",
},
base: {
service: process.env.SERVICE_NAME || "my-service",
env: process.env.NODE_ENV || "dev",
version: process.env.APP_VERSION || "unknown",
},
// Attach request context to every log line
mixin() {
const store = als.getStore();
if (!store) return {};
return {
correlation_id: store.correlation_id,
request_id: store.request_id,
trace_id: store.trace_id,
span_id: store.span_id,
sampled: store.sampled,
sample_rate: store.sample_rate,
tenant_id: store.tenant_id,
user_id_hash: store.user_id_hash,
};
},
});
export function loggingMiddleware({ infoSampleRate = 0.1 } = {}) {
return function (req, res, next) {
const correlation_id = correlationFromHeaders(req) || newId();
const request_id = newId();
// If you have tracing, parse traceparent here (or let OpenTelemetry do it)
const traceparent = req.headers["traceparent"];
const trace_id = traceparent ? traceparent.split("-")[1] : undefined;
const span_id = traceparent ? traceparent.split("-")[2] : undefined;
const sample_rate = infoSampleRate;
const sampled = stableSample(correlation_id, sample_rate);
// Example: hash user id (don’t log raw user id)
const rawUserId = req.headers["x-user-id"];
const user_id_hash = rawUserId
? crypto.createHash("sha256").update(String(rawUserId)).digest("hex")
: undefined;
const tenant_id = req.headers["x-tenant-id"];
const start = process.hrtime.bigint();
als.run(
{ correlation_id, request_id, trace_id, span_id, sampled, sample_rate, tenant_id, user_id_hash },
() => {
// Always return IDs to callers for cross-service correlation
res.setHeader("x-correlation-id", correlation_id);
res.setHeader("x-request-id", request_id);
res.on("finish", () => {
const durMs = Number(process.hrtime.bigint() - start) / 1e6;
// Access log: keep errors always; sample info
const status = res.statusCode;
const level = status >= 500 ? "error" : status >= 400 ? "warn" : "info";
const shouldLog = level !== "info" ? true : sampled;
if (shouldLog) {
baseLogger[level]({
log_class: "access",
req: {
method: req.method,
path: req.originalUrl || req.url,
headers: req.headers,
},
res: { status },
duration_ms: Math.round(durMs),
}, "request completed");
}
});
next();
}
);
};
}
// Helper: use this for app logs; respects sampling for info/debug if you want
export function appLog(level, obj, msg) {
const store = als.getStore();
const sampled = store?.sampled ?? true;
if ((level === "info" || level === "debug") && !sampled) return;
baseLogger[level](obj, msg);
}
import { als } from "./logger.js";
export async function fetchWithContext(url, options = {}) {
const store = als.getStore() || {};
const headers = new Headers(options.headers || {});
if (store.correlation_id) headers.set("x-correlation-id", store.correlation_id);
if (store.request_id) headers.set("x-request-id", store.request_id);
// If you use OpenTelemetry, it will usually inject traceparent automatically.
// Otherwise, you could forward the inbound traceparent as-is if present.
return fetch(url, { ...options, headers });
}
import express from "express";
import { loggingMiddleware, appLog } from "./logger.js";
const app = express();
app.use(express.json());
app.use(loggingMiddleware({ infoSampleRate: 0.1 }));
app.get("/health", (req, res) => {
appLog("info", { log_class: "app", event: "healthcheck" }, "health ok");
res.json({ ok: true });
});
app.listen(3000);
log_class and/or level.Example (conceptual):
logs-app-info-*: hot 7d, delete 30dlogs-app-error-*: hot 14d, warm 76d, delete 90dlogs-audit-*: warm/cold tiers, delete 365d (or archive to S3 first)traceparent over x-correlation-id)?