DEV Community

Cover image for Tracing in express.js
Rajika Imal
Rajika Imal

Posted on

Tracing in express.js

Tracing is tracking the details of each request. With tracing it is possible to track down the execution of the code for each user request in the context of a web application. This is important when debugging an application as it might be necessary to track a user and the corresponding path of the code. With threaded languages, this is quite straightforward with the thread id.

In Node.js, it is not simple as it is single threaded and depends on the event loop to execute asynchronously. However rtracer provides a straight forward solution to accomplish this.

rtracer provides APIs to use it in multiple frameworks such as express.js, and fastify.

To use it in express.js, rtracer has to be registered as a middleware. That's it. After that the id generated by rtracer can be used with any type of logger. An id is generated as follows,

app.use(rTracer.expressMiddleware());
app.get('/', (req, res) => {
  const requestId = rTracer.id();
  console.log(`Request Id: ${requestId}`);

  res.json({ status: true });
});
Enter fullscreen mode Exit fullscreen mode

This repository contains a minimal example that demonstrates rtracer with winston logger.

Top comments (0)