快速记录响应体 [英] express logging response body

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

问题描述

标题应该很自我解释。

为了进行调试,我希望表达能够为每个服务请求打印响应代码和正文。打印响应代码很简单,但打印响应体很复杂,因为响应体似乎不能作为属性使用。

For debugging purposes, I would like express to print the response code and body for every request serviced. Printing the response code is easy enough, but printing the response body is trickier, since it seems the response body is not readily available as a property.

以下内容不起作用:

var express = require('express');
var app = express();

// define custom logging format
express.logger.format('detailed', function (token, req, res) {                                    
    return req.method + ': ' + req.path + ' -> ' + res.statusCode + ': ' + res.body + '\n';
});  

// register logging middleware and use custom logging format
app.use(express.logger('detailed'));

// setup routes
app.get(..... omitted ...);

// start server
app.listen(8080);

当然,我可以轻松地在发出请求的客户端打印响应,但是我宁愿在服务器端也做。

Of course, I could easily print the responses at the client who emitted the request, but I would prefer doing at the server side too.

PS:如果它有帮助,我的所有回复都是json,但希望有一个解决方案适用于一般响应。

PS: If it helps, all my responses are json, but hopefully there is a solution that works with general responses.

推荐答案

不确定是否是最简单的解决方案,但您可以编写一个中间件来拦截写入响应的数据。确保您禁用 app.compress()

Not sure if it's the simplest solution, but you can write a middleware to intercept data written to the response. Make sure you disable app.compress().

function logResponseBody(req, res, next) {
  var oldWrite = res.write,
      oldEnd = res.end;

  var chunks = [];

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

    oldWrite.apply(res, arguments);
  };

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

    var body = Buffer.concat(chunks).toString('utf8');
    console.log(req.path, body);

    oldEnd.apply(res, arguments);
  };

  next();
}

app.use(logResponseBody);

这篇关于快速记录响应体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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