我使用pino-http记录请求,代码如下
import { pino } from 'pino';
import { pinoHttp } from 'pino-http';
import { v4 } from 'uuid';
export const logger = pino({
enabled: process.env.LOG_ENABLED === 'true',
formatters: {
level: (label) => {
return { level: label };
},
},
level: process.env.LOG_LEVEL || 'info',
name: process.env.LOGGER_NAME,
redact: {
paths: ['email', 'password', 'token'],
},
timestamp: pino.stdTimeFunctions.isoTime,
});
export const requestLogger = pinoHttp({
logger,
genReqId: function (req) {
req.id = v4();
return req.id;
},
customLogLevel: function (req, res, err) {
if (res.statusCode >= 400 && res.statusCode < 500) {
return 'warn';
} else if (res.statusCode >= 500 || err) {
return 'error';
} else if (res.statusCode >= 300 && res.statusCode < 400) {
return 'silent';
}
return 'info';
},
customProps: (req, res) => {
const accountId = req.user ? req.user.id : null;
const adminId = (req.session || {}).adminUser
? req.session.adminUser.id
: null;
return {
accountId,
adminId,
};
},
});
我希望能够通过其他函数跟踪请求id,因此我创建了一个代理记录器
const proxiedLogger = new Proxy(logger, {
get(target, property, receiver) {
target = context.getStore()?.get('logger') || target;
return Reflect.get(target, property, receiver);
},
});
const contextMiddleware = (req: Request, res: Response, next: NextFunction) => {
const child = logger.child({ requestId: v4() });
const store = new Map();
store.set('logger', child);
return context.run(store, next);
};
如何让pino-http对所有请求使用这个日志记录器?问题是pino-http附带了自己的genReqId方法
1条答案
按热度按时间6vl6ewon1#
有点晚了,但这是我如何解决这个问题的。
你可以使用pino-http的customProps来实现,基本上你想从存储中提取日志记录器,提取requestId然后返回它。