如何在fastify中为每个请求添加跟踪ID?

发布于 2025-01-10 08:10:08 字数 494 浏览 0 评论 0原文

我使用 fastify 作为我的应用程序的后端。我也使用 pino 记录器。

const fastify = require('fastify')({
logger: true
})

每次我编写 fastify.log.info("something") 时,我都需要使用一些跟踪 ID 查看日志(在我的终端中)。就像{message:something,trackingId:123}。整个请求中的跟踪 ID 应该相同。

我尝试在 fastify 记录器文档pino 记录器 没有成功。

Im using fastify as backend of my app. I also using pino logger.

const fastify = require('fastify')({
logger: true
})

I need that every time Im writing fastify.log.info("something") I need to see the log (in my terminal) with some trackingId. Like {message: something, trackingId: 123}. The tracking id should be the same throughout the request.

I tried to find how to do this in fastify logger docs and pino logger without success.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤君无依 2025-01-17 08:10:08

该代码将产生以下输出。请注意,我使用的是 request.log (不是 fastify.log)。这样fastify生成的request id就自动打印出来了。

const fastify = require('fastify')({
  logger: true,
  requestIdLogLabel: 'trackingId',
})

fastify.get('/', async (request, reply) => {
  request.log.info('Custom log message')
  return { hello: 'world' }
})
fastify.listen(8080)

输出:

{"level":30,"trackingId":"req-1","req":{"method":"GET","url":"/","hostname":"localhost:8080","remoteAddress":"127.0.0.1","remotePort":50743},"msg":"incoming request"}
{"level":30,"trackingId":"req-1","msg":"Custom log message"}
{"level":30,"trackingId":"req-1","res":{"statusCode":200},"responseTime":3.57566699385643,"msg":"request completed"}

req-id 由 Fastify 生成。您可以通过实现自己的 genReqId 来自定义其值函数

This code will produce the following output. Note that I'm using the request.log (NOT the fastify.log). In this way, the request id generated by fastify is printed out automatically.

const fastify = require('fastify')({
  logger: true,
  requestIdLogLabel: 'trackingId',
})

fastify.get('/', async (request, reply) => {
  request.log.info('Custom log message')
  return { hello: 'world' }
})
fastify.listen(8080)

Output:

{"level":30,"trackingId":"req-1","req":{"method":"GET","url":"/","hostname":"localhost:8080","remoteAddress":"127.0.0.1","remotePort":50743},"msg":"incoming request"}
{"level":30,"trackingId":"req-1","msg":"Custom log message"}
{"level":30,"trackingId":"req-1","res":{"statusCode":200},"responseTime":3.57566699385643,"msg":"request completed"}

The req-id is generated by Fastify. You can customize its value by implementing your own genReqId function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文