Per request logging in Node.js

前端 未结 3 890
轻奢々
轻奢々 2021-02-13 00:46

I am an experienced Java developer picking up Node.js and making the shift to the asynchronous model. Most things are going fine except for logging. I cannot find anything sim

3条回答
  •  無奈伤痛
    2021-02-13 01:24

    I got into this same problem some time ago, and finally I could spend sometime researching it. The @ibash approach and his post put me in the lead to solve the problem I had (thanks for your help). I only walked some steps more in order to print in the logs automatically a unique id per request. In your case you can add origin and destination IP and all information needed to each request, using same approach and print it automatically in all logs.

    My approach: - As @ibash explained, I used continuation-local-storage to share information among all the modules per request. So I generate a unique id per request and store it in a namespace created with this library - I wrapped the Winston library (in a very simple way) in order to recover the information from the namespace shared and override all Winston methods I use adding to the string the unique Id. Obviously in your case you should add all the info you need and you have stored previously in the namespace of the library.

    As the problem was a little complex to explain to people no familiarize with all these things, I wrote it down in a post with a clear example that you can reuse if you want. Winston wrap could be really useful: Express.js: Logging info with global unique request ID – Node.js

    I hope you can reuse my code and perhaps in the future Express implements a solution for this.

提交回复
热议问题