For a detailed explanation of the concepts used in this repository, read the accompanying article: Logging with Pino and AsyncLocalStorage in Node.js.
An example Node.js (Express) application that implements contextual logging by attaching a request ID to every log line. It uses AsyncLocalStorage together with Pino.
- Clone this repository:
git clone [email protected]:Maximization/contextual-logging-nodejs.git && cd contextual-logging-nodejs
- Install NPM dependencies:
npm install
- Start the Node.js application:
npm start
- Visit
http://localhost:3000/users/1
in your browser and hit refresh a few times. - View the logs in your terminal. Each log line will have a unique request ID present.
{...,"requestId":"da672623-818b-4b18-89ca-7eb073accbfe","userId":1,"msg":"Fetching user from DB"}
{...,"requestId":"da672623-818b-4b18-89ca-7eb073accbfe","user":{...},"msg":"User found, sending to client"}
{...,"requestId":"01107c17-d3c8-4e20-b1ed-165e279a9f75","userId":1,"msg":"Fetching user from DB"}
{...,"requestId":"01107c17-d3c8-4e20-b1ed-165e279a9f75","user":{...},"msg":"User found, sending to client"}