Express logging with storing the request informati

2019-09-10 07:13发布

Background

Yes, there are a lot of different Node.js logging library winston, bunyan and console.log. It's easy to log down the information of the specific request when it has called and when and what information would be in response.

The problem

The problem begins with the sub function calls. When under one request your calling multiple functions which also uses the same logging, how would you pass the request meta - data to these log calls (function parameters seems to be one possible way but these are really messy) ?

Example

Small visual for coders:

// Middleware to set some request based information
app.use(function (req, res, next) {
  req.rid = 'Random generated request id for tracking sub queries';
});

app.get('/', function (req, rest) {

  async.series({
    'users': async.apply(db.users.find),
    'posts': async.apply(db.posts.find),
  }, function (err, dbRes) {
     console.log('API call made ', req.rid)
     res.end(dbRes);

  });


});


// Now the database functions are in other file but we also need to track down the request id in there
(db.js)

module.exports = {
   users: {
      find: function () {
         console.log('Calling users listing ', req.rid); // ERROR this is not possible to access, not in this scope 
         // Make query and return result
      }

   },

   posts: {
      find: function () {
         console.log('Calling post listing ', req.rid); // ERROR this is not possible to access, not in this scope 
         // Make query and return result
      }

   }

};

1条回答
太酷不给撩
2楼-- · 2019-09-10 07:19

You can log your requests with simple conf in your app.js with;

app.use(function(req, res, next){
  console.log('%s %s', req.method, req.url);
  next();
});

However, you need to provide logs for specific functions in your controller.

查看更多
登录 后发表回答