Is Bunyan log.child the right use case?

I watched bunyan to enter my nodejs application. I tried, and everything seems to work very well. I skipped the section on log.child , but now I'm trying to figure out how to use it. I think the goal is to allow me to provide some kind of special identifier for the journal entry so that I can uniquely identify how this journal is associated with any other journal entry.

If that were the case, I would suggest that I use log.child in every request:

 var bunyan = require('bunyan'); var log = bunyan.createLogger({name: 'myapp'}); router.post('/submit', function(req, res) { var logChild = log.child({reqId: uuid.v4()}); logChild.info({ req:req }, req.user.name + ' has called /submit'); saveData(req) .then(function(data) { logChild.info({data: data}, req.user.name + ' has saved to DB successfully in /submit'); res.json({'success': 'Saved!'}); }) .error(function(err) { logChild.error({ err: err }, req.user.name + ' has caused an error in /submit '); res.status(500).json("error": err}); }); }); 

Thus, if the user Bob POSTs before /submit twice within 30 seconds, there will be some context that distinguishes between two different calls in the log file.

That is, I will see something like this (with context):

 Bob has called /submit uuid: 109156be-c4fb-41ea-b1b4-efe1671c5836 Bob has called /submit uuid: 49dlsd7i-dapd-fdio-fei0-sd59fd0ph34d Bob has saved to DB successfully in /submit uuid: 109156be-c4fb-41ea-b1b4-efe1671c5836 Bob has caused an error in /submit uuid: 49dlsd7i-dapd-fdio-fei0-sd59fd0ph34d 

Instead (without context):

 Bob has called /submit Bob has called /submit Bob has saved to DB successfully in /submit Bob has caused an error in /submit 

So, for all my routes in my Nodejs application, I would create a logChild object and then use logChild to write entries in that route.

I got it right and implementation of the use log.child ?

+6
source share
1 answer

You seem to be using log.child accordingly. One suggestion I could make to help you โ€œuniquely identify how this log is associated with any other log entryโ€ is to bind log to the req object. Thus, if you have other middleware, you can access the same log with the same unique identifier from several places. For instance:

 var log = bunyan.createLogger({name: 'myapp'}); router.use(function(req, res, next) { req.log = log.child({ user : req.user.id }); }); router.post('/submit', function(req, res) { req.log.info('submitted request at ' + Date.now()); }); 

Now you will see { user : some_user_id, msg: 'submitted request at 01/03/15' } in your logs, which makes it possible to link any middleware in the request chain with one user using the req.log object.

+3
source

Source: https://habr.com/ru/post/986530/


All Articles