我正在使用fastify
withnext.js
并且我需要包括跟踪(requestId
到目前为止是问题)。我现在正在做的是创建一个fastify
onRequest 钩子并生成一个requestId
值并将其设置在请求对象中(也可以作为请求标头)。我想要访问这个请求对象有两个原因:
- 在记录器对象中(
pino
在这种情况下,我想requestId
在所有自定义服务器端日志中包含 )。 - 在需要向其他服务发出的所有请求中,都需要包含
requestId
in 标头。
也许我错过了一些微不足道的事情,而且我没有以最好的方式做到这一点。
这里有一些片段
这就是我生成 reqId 的方式
const fastify = fastifyFactory({
logger, // logger configuration (Pino instance with custom configuration, see below)
genReqId: () => {
return Math.random()
.toString(36)
.slice(-6);
}
});
皮诺实例
const pino = require('pino');
const logger = pino({
messageKey: 'message',
prettyPrint: true,
changeLevelName: 'severity',
useLevelLabels: true,
base: {
serviceContext: {
service: 'web'
}
},
level:'info'
});
module.exports = {
logger
};
这是一个插件,用于获取生成的 reqId 并将其设置为请求对象中的查询属性
const tracing = function tracing(fastify, opt, next) {
fastify.addHook('onRequest', (req, res, nextRequest) => {
const { id } = req;
const logger = fastify.log.child({ reqId: id });
req.query.reqId = id;
fastify.log = logger; //overrides the current fastify logger to include the reqId in all custom logs
nextRequest();
});
next();
};
tracing[Symbol.for('skip-override')] = true;
module.exports = tracing;
使用时我没有问题,fastify.log.info(...)
因为在每个请求中如何覆盖记录器,它将包含reqId
作为子日志。问题是我想创建一个通用记录器以在任何部分使用,而 Fastify 记录器在 React 组件中不可用(例如在 处写入日志getInitialProps
)。另一个重要的想法是我需要reqId
在我发送给其他服务的所有请求中包含这个(例如:在获取数据时),这就是为什么我尝试将此值存储在请求对象中但需要获取它的原因。