Observability

Making failures diagnosable: logging you can search and trust

I measured what our logs could and could not tell an operator, then standardized them in two weeks: safe fields, request lineage, one path to Sentry, and tests that hold the line.

The problem

No single incident prompted this. It was a planned step in a larger modernization program I ran. The purpose was to make failures diagnosable before hardening the asynchronous and AI paths.

I began by measuring. In the critical areas there were 3,218 production log calls, and a strict scan found only 833 that started with the name of the function that wrote them. The field naming where a log came from had 260 different spellings.

The baseline also found real leaks. The Google sign-in callback logged a refresh token. One AI feature logged the model's full response when parsing failed. Sixteen places attached a user's raw email address to error reports. Over fourteen days, 98.5% of production logs named a source but only 46.1% carried a request ID.

The logger itself was thin. It truncated long values but had no recursive redaction, no byte limit and no tests of its own. Thirty files sent errors to Sentry directly. An incoming request ID was accepted without validation.

Two decisions first

I reused the existing logger, Sentry and analytics instead of adding a new stack. No parallel logger.

I rejected logging at the repository layer. Logging every row access would create duplication and privacy risk, not observability.

A message you can grep

Every message starts with the name of the function that wrote it and labels every ID it includes. A bare ID collides across tables. The label tells you which column to query.

The message conventionIllustrative
// functionName: <what happened> <entity> <id type> <id>
const log = makeLogger({ source: 'tasks.update', taskId, userId });

log.error(`updateTask: failed to update task id ${taskId}`, { error });

// Anything that is not a labelled ID goes in the fields, not the message.
log.info(`createTemplate: created template id ${id}`, { name });

I kept 887 older source names as they were, so saved searches, alerts and dashboards kept working. New names follow one lower-case dotted pattern.

Redaction inside the logger

Redaction lives inside the logger, so no caller has to remember it. Every value passes through a recursive sanitizer. It removes emails, tokens and secrets, caps each string at 4,000 bytes, stops at eight levels of nesting and keeps fifty entries per collection.

Redaction happens inside the loggerIllustrative
function sanitize(value: unknown, depth = 0, key?: string): unknown {
  if (key && looksSensitive(key)) return '[REDACTED]';

  if (typeof value === 'string') {
    return truncate(redactSecretsAndEmails(value), MAX_BYTES);
  }
  if (typeof value !== 'object' || value === null) return value;
  if (depth >= MAX_DEPTH) return '[MaxDepth]';
  if (alreadySeen(value)) return '[Circular]';

  return mapEntries(firstN(value, MAX_ENTRIES), ([k, v]) => [
    k,
    sanitize(v, depth + 1, k),
  ]);
}

Keys matter as much as values. A field named like a token or password is replaced whole. So is a field that holds content, such as a body, a prompt or a transcript. Circular references are cut instead of followed.

Lineage into background jobs

A request's identity follows it into background jobs through three allowlisted fields: the request ID, the parent operation and the parent route. Anything else is rejected. A scheduled job with no originating request does not invent one.

The three-field envelopeIllustrative
interface AsyncContext {
  requestId: string;
  parentOperation: string;
  parentRoute: string;
}

// Copy only these three fields into a background event. Nothing else
// from the request is allowed to ride along.
function buildAsyncContext(request: RequestContext): AsyncContext {
  return {
    requestId: request.requestId,
    parentOperation: request.operation,
    parentRoute: request.route,
  };
}
An API request passes three lineage fields to a background job. Both write through one logger, whose recursive sanitizer runs before anything reaches the logs. Errors reach Sentry through one helper. Scanner tests fail when new code breaks the contract.
One logger, one sanitizer, one path to Sentry, and tests that keep new code inside the contract.

On the receiving side the envelope is rebuilt from those three fields and validated. If any one is invalid or oversized, the whole envelope is dropped.

Errors take one path too. All of them reach Sentry through a single helper, which passes the original exception through unchanged so issue grouping is preserved. Redaction happens later, in Sentry's own event processing.

Tests that hold the line

Each rule is held by a scanner test that fails when new code breaks it. A message must start with its function name and label its IDs. A new place that emits telemetry must be registered.

A check that enforces the conventionIllustrative
it('requires a fixed function name and a labelled id', () => {
  // A prefix built at runtime cannot be searched for.
  expect(check('${name}: starting for contract id ${id}')).toContain(
    'dynamic function prefix',
  );
  // An id with no label could belong to any table.
  expect(check('sendReceipt: starting for ${id}')).toContain('unlabelled id');

  expect(check('sendReceipt: starting for contract id ${id}')).toEqual([]);
});

I added the standard envelope for API routes in one central place instead of editing each route. Twelve routes that could not take it are listed as explicit exceptions, not silently skipped.

I also wrote an operator runbook for tracing a failure across systems. It starts from grouped counts and never displays message bodies or payloads, so an investigation does not itself expose customer data.

What changed

The work ran from July 17 to July 31, 2026, as 54 merged pull requests, all mine. I ran it with AI coding agents working from one master brief, with separate agents implementing and reviewing. I approved scope and sequencing.

What I can't tell you from the record: whether debugging got faster. No incident is documented as resolved with this work, and no time-to-diagnose measure exists.