I am trying to trace each HTTP request in my REST API using Loopback 4 in order to log them in the controllers using log4js, just like this:
[2020-05-05T19:21:52.191] [INFO] [request-id:47e9a486-1243-1c07-3ac0-0acc9cce2c0e] user.controller.ts - starting request validation
[2020-05-05T19:21:52.191] [INFO] [request-id:1dc81e45-093a-8009-42d2-e545c3a10c9d] user.controller.ts - starting request validation
[2020-05-05T19:21:53.126] [INFO] [request-id:47e9a486-1243-1c07-3ac0-0acc9cce2c0e] user.controller.ts - request validation success
[2020-05-05T19:21:53.145] [ERROR] [request-id:1dc81e45-093a-8009-42d2-e545c3a10c9d] user.controller.ts - request validation failed
The main problem here is the [request-id:UUID]
part, since Node.js sometimes mixes up the logs and I am not able to identify which of them belong to the same request. I have found some solutions for Express applications, but I could not find a way to make that work with Loopback 4 and log4js:
- https://itnext.io/request-id-tracing-in-node-js-applications-c517c7dab62d
- https://solidgeargroup.com/en/express-logging-global-unique-request-identificator-nodejs/
- tracking request flow by ID in node.js
The solution might involve the use of the Sequence handler, but I could not figure out how to do it yet. Some hint of injecting the Request object: https://github.com/strongloop/loopback-next/issues/1881#issuecomment-431384142