在 Node.js/Express 中记录所有请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42099925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:58:51  来源:igfitidea点击:

Logging all requests in Node.js/Express

jsonnode.jsexpressloggingwinston

提问by Julien

In my small node.js application, using express, I wanted to log all the incoming requests, so I ended up with this:

在我的小 node.js 应用程序中,使用 express,我想记录所有传入的请求,所以我最终得到了这个:

var bodyParser = require('body-parser');

module.exports = function(app) {
   app.set("port", 50001);
   app.set("json spaces", 2);
   app.use(bodyParser.json());
   app.use(function (error, req, res, next) {
      app.logger.info("received from "+req.get("X-Forwarded-For")+" : "+req.method+" "+req.originalUrl+" (Authorization: "+req.get("Authorization")+")");
      //does not work if json is malformed
      //app.logger.info("content :"+JSON.stringify(req.body));
      if (error /*instanceof SyntaxError*/) {
         res.status(400);
         app.logger.error(error);
         res.json({ error:{msg: error.message}});
      } else {
         next();
      }
   });
   app.use(app.auth.initialize());
};

Unfortunately, I only get the logs via the app.logger.infoline when there's an error (in my case a malformed JSON string in the body). What am I missing here?

不幸的是,我只有app.logger.info在出现错误时才通过该行获取日志(在我的情况下,正文中是格式错误的 JSON 字符串)。我在这里缺少什么?

回答by jfriend00

Expressjs adapts its functionality based on what type of callback you give it (this is not common in JS libraries so it is not surprising that people get confused by it).

Expressjs 根据您提供的回调类型调整其功能(这在 JS 库中并不常见,因此人们对此感到困惑也就不足为奇了)。

If you do this where your callback has four arguments:

如果你这样做,你的回调有四个参数:

app.use(function(error, req, res, next) {...});

then Express assumes this is an error-only middleware handler and will only be called when there are errors. In the express doc, see the section labeled Error-handling middleware. Note this specific part of that page:

然后 Express 假定这是一个仅错误的中间件处理程序,并且只会在出现错误时调用。在express 文档中,请参阅标记为Error-handling middleware的部分。请注意该页面的这一特定部分:

Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)):

以与其他中间件函数相同的方式定义错误处理中间件函数,除了使用四个参数而不是三个参数,特别是使用签名(err、req、res、next)):

And, here's a whole section of the documentation devoted to error handling middleware.

而且,这里有一整节专门介绍错误处理中间件的文档。

If you use just three arguments:

如果您只使用三个参数:

app.use(function(req, res, next) {...});

then, it is a normal middleware that is called when there are not errors. I'm not sure if they provide a single way to get both. But, certainly as a workaround, you could put your logging code into a function and then call that function from two separate middleware handlers, one for errors and one for non-errors.

然后,它是一个正常的中间件,在没有错误时调用。我不确定他们是否提供了一种方式来获得两者。但是,当然作为一种解决方法,您可以将日志记录代码放入一个函数中,然后从两个单独的中间件处理程序调用该函数,一个处理错误,一个处理非错误。

回答by jamesjara

You could use try/catch

你可以使用 try/catch

try {
   var jsonBody = JSON.stringify(req.body);
   app.logger.info("content :" + jsonBody);
} catch (err) { 
    app.logger.error("content error, error type: invalid json, error msg:" + err);
}