Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS log unique request trace

I want to implement logging in NestJS HTTP service so that each incoming request gets its traceId and it gets logged with the log line. Best would be something like this:

[LogInterceptor, traceId=b57847d0-ed31-11e9-969e-7dd13d8a9c1e] Before getUser at 1570911778049.
[UsersController, traceId=b57847d0-ed31-11e9-969e-7dd13d8a9c1e] Getting user...
[UsersService] Looking for user by id [testLocal]...

Here, as you can see, I'm missing traceId in UsersService log line because I don't know how to reasonably deal with full vertical using request based logger without using Scope.REQUEST injection scope. I would try to avoid cascading all my providers to REQUEST scope for performance reasons.

And I managed to get that far by intercepting incoming request, assigning a traceId to it, instantiating a logger with traceId and attaching it to request. Then in the controller, I inject a custom parameter decorator (with controller class name so it picks up the first part of logger context).

And due to nature of NodeJS, I believe that's as far as I can get. I'm coming from Java world where we could deal with this stuff using Threads and their local variables or different Thread based solutions. What's the best solution for that in this ecosystem?

Use case is production grade logging system which is able to correlate logs from different parts of the code based on unique request identifier.

EDIT: Some time ago I've seen Async Hooks in NodeJS. I forgot to go in that direction during this investigation. But on quick look, they're still experimental feature. Any comments on solutions based on them?

like image 280
maricn Avatar asked Oct 12 '19 21:10

maricn


1 Answers

You can try nestjs-pino, it logs every response with headers, and also has request context when using it as LoggerService, it works on top of async_hooks (cls-hooked) and not using Scope.REQUEST.

Some time ago I've seen Async Hooks in NodeJS. I forgot to go in that direction during this investigation. But on quick look, they're still experimental feature. Any comments on solutions based on them?

cls-hooked has more then 200,000 weekly installs, and I'm using nestjs-pino in production (with nodejs 12), and have not any issues with it so far.

Update: now the library use AsyncLocalStorage which is marked as stable api since [email protected].

Disclaimer: I'm the author.

like image 146
iamolegga Avatar answered Oct 20 '22 15:10

iamolegga