简体   繁体   English

如何使用Winston / Morgan记录JSON HTTP响应

[英]How to log JSON HTTP Responses using Winston/Morgan

I'm using Winston and Morgan for all the back-end logging in Sails.js and I need to be able to log the responses from HTTP get requests. 我将Winston和Morgan用于Sails.js中的所有后端日志记录,我需要能够记录来自HTTP get请求的响应。 I need to log them in a file. 我需要将它们记录在文件中。 My logFile currently takes shows all the http requests but it does not show the responses. 我的logFile当前使用显示所有http请求,但不显示响应。 I have searched all the options for Morgan and Winston and can't find a way/option to do this. 我搜索了Morgan和Winston的所有选项,但找不到执行此操作的方法/选项。 I was just wondering if any of you had any advice on how to accomplish this? 我只是想知道你们中的任何人对如何做到这一点有什么建议吗? Thanks! 谢谢!

You can write a middleware function for ExpressJS that will log the body once a response is sent. 您可以为ExpressJS编写一个中间件函数,一旦发送响应,它将记录主体。 Basing it off of Node's http module to see how Connect (and therefore Express) manages the response body (which is a stream): you can hook into the two methods that write to that stream to grab the chunks and then concat/decode them to log it. 将其基于Node的http模块,以查看Connect(以及Express)如何管理响应主体(即流):您可以使用两种写入该流的方法来捕获流,然后将其连接/解码为记录下来。 Simple solution and could be made more robust but it shows the concept works. 简单的解决方案可能会变得更强大,但是它显示了该概念的有效性。

function bodyLog(req, res, next) {
  var write = res.write;
  var end = res.end;
  var chunks = [];

  res.write = function newWrite(chunk) {
    chunks.push(chunk);

    write.apply(res, arguments);
  };

  res.end = function newEnd(chunk) {
    if (chunk) { chunks.push(chunk); }

    end.apply(res, arguments);
  };

  res.once('finish', function logIt() {
    var body = Buffer.concat(chunks).toString('utf8');

    // LOG BODY
  });

  next();
}

And then set it before any routes are assigned in the main app router: 然后在主应用路由器中分配任何路由之前进行设置:

app.use(bodyLog);
// assign routes

I would assume you could also use this as an assignment for a variable in Morgan but I haven't looked into how async variable assignment would work. 我假设您也可以将其用作Morgan中变量的赋值,但我尚未研究异步变量赋值的工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM