Express logging with storing the request information

早过忘川 提交于 2020-01-07 03:58:10

问题


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:


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.



来源:https://stackoverflow.com/questions/22224641/express-logging-with-storing-the-request-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!