A log for a request looks like this:
Received a new product Widget-1
Started to store product
POST /products 200 52.240 ms - 2
Product stored
Where the first, second and fourth lines are logs I created using console.log. The third is done by Morgan.
My problem is that the (asynchronous) function that stores the products in the db is relatively slow so I have logs like this
Received a new product Widget-1
Started to store product
POST /products 200 52.240 ms - 2
Received a new product Widget-2
Started to store product
POST /products 200 52.240 ms - 2
Product stored
Product stored
How can I tag each log line so I can group the logs of a request easily? Something like
[11111] Received a new product Widget-1
[11111] Started to store product
[11111] POST /products 200 52.240 ms - 2
[aaaaa] Received a new product Widget-2
[aaaaa] Started to store product
[aaaaa] POST /products 200 52.240 ms - 2
[11111] Product stored
[aaaaa] Product stored
The tag can any format, I just want to filter the lines that belong to the same request.
I tried this in Express creating a middleware that assigned a random number to a req.id and used that number in each console.log, for example:
console.log(`[${req.id}] Started to store product`)
But I would prefer to define the tag in a middleware or configuration, and then use console.log("Started to store product")
via Victor
No comments:
Post a Comment