正如@moka 所说,在每个请求中使用请求ID 是解决问题的关键。另一种抽象所有这些的方法是利用 http-context 和 uuid
所以在所有中间件之前在 httpContext 中设置一个 UUID(设置为应用程序中间件而不是路由器中间件)。现在您可以在代码中的任何位置获取 uuid 并记录它。
这是我使用的示例实现
您可以在这里获得完整的参考资料uuid in request
const uuid = require('node-uuid');
const httpContext = require('express-http-context');
....
this.expressApp.use(httpContext.middleware);
this.expressApp.use((req, res, next) => {
httpContext.set('reqId', uuid.v4());
next();
});
现在我已经在我的自定义 pino 记录器中使用了这里设置的 reqId'
public infoLogService (fileName): pino.Logger {
return pino({
level: 'info',
name: this.appService.getApp_name(),
messageKey: 'XXX-Logs',
base: {pid: process.pid, hostname: os.hostname,
timestamp: this.getTimeStamp(),
appName: this.appService.getApp_name(),
fileName: fileName,
request_id: **isNullOrUndefined(httpContext.get('reqId'))** ? 'Not an actual request ' : httpContext.get('reqId')
},
enabled: true,
useLevelLabels: true,
});
}
如果 reqId 为 null,则表示记录器已插入到启动 express 应用程序之前使用的代码中。希望您可以将其用作替代解决方案