Correlation ID Async Context

Propagate a correlation id across async calls with AsyncLocalStorage so every log line carries the request identity.

JavascriptResilience

Code

snippet
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';

export const context = new AsyncLocalStorage();

export function withCorrelationId(id, fn) {
  const correlationId = id || randomUUID();
  return context.run({ correlationId }, fn);
}

export function currentCorrelationId() {
  const store = context.getStore();
  return store ? store.correlationId : undefined;
}

export function log(level, message, extra = {}) {
  const correlationId = currentCorrelationId();
  const record = { level, message, correlationId, ...extra };
  process.stdout.write(JSON.stringify(record) + '\n');
}