HeadlinesBriefing favicon HeadlinesBriefing.com

Adding userId and transactionId to console.log without refactoring

DEV Community •
×

A developer explains how logging becomes unreadable in scaled JavaScript servers. When hundreds of concurrent requests generate thousands of identical `console.log()` lines, debugging turns into guesswork. The core problem is missing context—without user or transaction IDs, you can't trace specific actions through your system.

The solution involves a Node.js package, @purpleowl-io/tracepack, that adds context automatically. By importing and calling `replaceConsole()` and `loggerMiddleware()`, all existing logs gain userId and txId fields. This works via AsyncLocalStorage, which attaches context to the execution path, not individual function calls, surviving async operations like promises and database calls.

For background jobs, you can explicitly set context with `withContext()`. The output is structured JSON, filterable with tools like jq. This approach avoids a massive refactor, offering a practical fix for teams where concurrency has made traditional logging ineffective. It's a targeted tool for a common scaling pain point.