如何使用 express-winston 在 msg 对象中记录请求正文 (req.body)?



我正在尝试通过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}

但是我现在不希望整个元填满我的日志。

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

由于您现在已经收到警告,您可以通过添加来添加它

expressWinston.requestWhitelist.push('body');

加载expressWinston之后和app.usingexpressWinston.logger之前的某个地方.

最新更新