4

我想在我的日志文件中记录响应正文

我已经尝试过 morgan-body 但我想将响应记录在文件而不是控制台中

以下代码将记录请求正文,那么是否也可以记录响应?

morgan.token('body', function (req, res) { return JSON.stringify(req.body) });

app.use(morgan(':method :url :status :response-time ms - :res[content-length] :body - :req[content-length]', { 
  stream: logger.successLogStream,
  skip: function (req, res) { return res.statusCode >= 400 }
 }));

 app.use(morgan(':method :url :status :response-time ms - :res[content-length] :body - :req[content-length]', { 
  stream: logger.errorLogStream,
  skip: function (req, res) { return res.statusCode < 400 }
 }));

例如,我想记录以下错误消息

return res.status(400).send({ "message": "Campaign id is not defined" })
4

3 回答 3

1

覆盖 res.send / res.json 方法,自定义 :res-body 并注意将 morgan 放在路由之后

morgan.token('resBody', (req, res) => res.resBody);
res.send = (...args) => {
    res.oldsend(...args);
    res.resBody = JSON.stringify(args);
};
app.use(routes)
app.use(morgan(...))
于 2019-07-25T03:36:03.997 回答
1

你可以用这个

const app = express()
const originalSend = app.response.send

app.response.send = function sendOverWrite(body) {
  originalSend.call(this, body)
  this.__custombody__ = body
}

morgan.token('res-body', (_req, res) =>
  JSON.stringify(res.__custombody__),
)

...

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan(loggerFormat, { stream: logStream }))
app.use(...routers)
于 2020-07-16T06:03:56.850 回答
1

使用节点 v16 和摩根自定义日志格式更新上述答案

中间件.ts

 export const setResponseBody = (req: any, res: any, next: any) => {
    const oldWrite = res.write,
        oldEnd = res.end,
        chunks: any = [];

    res.write = function (chunk: any) {
        chunks.push(Buffer.from(chunk));
        oldWrite.apply(res, arguments);
    };

    res.end = function (chunk: any) {
        if (chunk) {
            chunks.push(Buffer.from(chunk));
        }
        const body = Buffer.concat(chunks).toString('utf8');
        res.__custombody__ = body;
        oldEnd.apply(res, arguments);
    };
    next();
};

应用程序.ts

morgan.token('responseBody', function (req, res: any) {
    if (res['statusCode'] != 200) {
        return res['__custombody__'] || null;
    }
    return null;
});
const app = express();
app.use(morgan('responseBody=:responseBody'));
于 2021-10-13T14:06:49.947 回答