快速记录并存储请求信息 [英] Express logging with storing the request information

查看:77
本文介绍了快速记录并存储请求信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,有很多不同的Node.js日志记录库winston,bunyan和console.log.记录特定请求的信息,何时调用以及何时响应的信息很容易记录下来.

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 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) ?

编码人员的视觉效果小:

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
      }

   }

};

推荐答案

您可以使用以下简单的conf将请求记录在app.js中:

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.

这篇关于快速记录并存储请求信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆