【问题标题】:How do I log the request body (req.body) in the msg object using express-winston?如何使用 express-winston 在 msg 对象中记录请求正文 (req.body)?
【发布时间】:2019-10-28 17:22:44
【问题描述】:

我正在尝试通过express-winstonmsg: 对象记录{{ req.body }}

我已经使用 expressWinston.requestWhitelist.push('body'); 将正文列入白名单,但它仍未出现在日志中。

export const accessLogger = (router: Router) => {
    expressWinston.requestWhitelist.push('body');
    router.use(expressWinston.logger({
        level: "info";
        format: winston.format.simple(),
        transports: [
            new winston.transports.Console()
        ],
        meta: false,
        metaField: null!,
        msg: "HTTP {{ req.method }} {{ req.url }} {{ req.body }}",
        expressFormat: true
    }));
}

使用:

curl -X POST -H "Accept: application/json" -d '{"test": "value"}' http://localhost:someport'

目前在日志中如下所示:

info: POST / 200 1ms

应该看起来像:

info: POST / 200 1ms {\"test\": \"value\"}

如果我使用meta:true 启用meta 我知道并看到它在那里:

info: POST / 200 1ms {"req":{"url":"/","headers":{"host":"localhost:someport","user-agent":"curl/7.63.0","accept":"application/json","content-length":"17","content-type":"application/x-www-form-urlencoded"},"method":"POST","httpVersion":"1.1","originalUrl":"/","query":{},"body":{"{\"test\": \"value\"}":""}},"res":{"statusCode":200},"responseTime":1}

但我现在不想让整个元数据填满我的日志。

【问题讨论】:

标签: javascript node.js typescript express winston


【解决方案1】:

req.body 默认情况下不包括在内,因为它通常包含不应记录的内容,例如密码,因此请确保在执行此操作之前要执行此操作。

既然你现在已经被警告了,你可以通过添加来添加它

expressWinston.requestWhitelist.push('body');

在加载expressWinston 之后和app.using expressWinston.logger 之前的某个位置。

【讨论】:

  • 查看我的帮助代码:router.use(expressWinston.logger({ transports: [ new winston.transports.File({filename: 'log.json'}) ],格式:winston.format .combine(winston.format.colorize(),winston.format.json())})); expressWinston.requestWhitelist.push('body'); router.get('/', function(req, res, next) { res.write('这是一个正常的请求,它也应该记录到控制台'); res.end(); });跨度>
猜你喜欢
  • 2020-06-21
  • 2019-02-17
  • 1970-01-01
  • 2018-08-02
  • 2019-07-03
  • 2018-06-20
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
相关资源
最近更新 更多