Skip to content

Add request ID middleware and correlate logs with request context #34

Description

@prodbycorne

Overview

Logs from concurrent requests are interleaved with no way to correlate them. Adding a request ID to every log line allows tracing a single request's journey through the system, essential for debugging production issues.

Current Problem

[INFO] Fetching price for XLM
[INFO] Fetching price for USDC
[ERROR] CoinGecko fetch failed
[INFO] Cache hit for XLM

Which request caused the CoinGecko failure? Impossible to tell.

Solution

  1. Generate a request ID on every incoming request (nanoid or crypto.randomUUID())
  2. Attach to req.id via middleware early in the chain
  3. Pass to logger via async-local storage (ALS) so child log calls inherit it:
// src/middleware/requestId.js
const { AsyncLocalStorage } = require('node:async_hooks');
const requestContext = new AsyncLocalStorage();

function requestIdMiddleware(req, res, next) {
  req.id = crypto.randomUUID();
  res.setHeader('X-Request-ID', req.id);
  requestContext.run({ requestId: req.id }, next);
}
  1. Update src/logger.js to include requestId from ALS in every log line:
const child = logger.child({
  requestId: requestContext.getStore()?.requestId ?? 'system'
});

After this change:

{ "level": "error", "requestId": "f8a2-...", "msg": "CoinGecko fetch failed" }
{ "level": "info",  "requestId": "a1b3-...", "msg": "Cache hit for XLM" }

Acceptance Criteria

  • X-Request-ID header on every response
  • Request ID propagated to all log lines within that request
  • Background tasks log with requestId: 'system'
  • Test: log output includes matching requestId for a given request
  • ALS used (not req passed manually through every function)

Metadata

Metadata

Assignees

Labels

GrantFox OSSIssue tracked in GrantFox OSSMaybe RewardedIssue may be eligible for a GrantFox rewardOfficial CampaignCampaign: Official CampaignobservabilityLogging, metrics, tracing, monitoring

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions