How to append a unique_id to my express node logs

2019-02-10 09:14发布

问题:

I've an Express app. I'd like to trace all the loggings that were made by a single request.

Apache has a module called mod_unique_id which injects in the request headers a special one containing a unique hash. I'd like to use such hash when logging (anything).

For example if an user is assigned by apache the unique_id valued "abcdefg" and somewhere in my code (controller, model, or anything) i generate a debug log i'd like to have "abcdefg" attached to every log entry.

The only idea that pops in my mind is to create a logger instance using app.use() and pass that logger instance to ALL the functions that are needed (models,libs etc) to generate the proper response.

Unfortunately this will cause me to rewrite a lot of the code to let old functions accept this new logger instance.

Does anyone know a better way of having a single "logger" instance per "request" which is accessible somehow without passing this "per-request-created-logger" to anything ?

PS: I'm currently using winston to log