日志

日志默认是未启用的,你可以在创建 fastify 实例时传入 { logger: true } 或者 { logger: { level: 'info' } } 来启用日志功能。

由于 Fastify 专注于性能,因此使用 pino 作为日志记录器,默认日志级别在启用时设置为“info”。

启用日志记录器非常简单:

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

fastify.get('/', options, function (req, reply) {
  req.log.info('Some info about the current request')
  reply.send({ hello: 'world' })
})

如果想要传递配置选项给日志记录器,只需将 logger 选项传递给 Fastify 。可以在 Pino 文档中找到所有配置选项。如果想要将自定义流传递给Pino实例,只需将流字段添加到日志记录器对象即可。

const split = require('split2')
const stream = split(JSON.parse)

const fastify = require('fastify')({
  logger: {
    level: 'info',
    stream: stream
  }
})

fastify.get('/', options, function (req, reply) {
  req.log.info('Some info about the current request')
  reply.send({ hello: 'world' })
})

默认情况下,fastify为每个请求添加一个id,以便于跟踪。如果存在“request-id”头,则使用其值,否则生成新的增量ID。此外,genReqId选项可用于自己生成请求ID。它将接收到作为参数的传入请求。

let i = 0
const fastify = require('fastify')({
  logger: {
    genReqId: function (req) { return i++ }
  }
})

可以提供自定义的日志记录器实例。自定义的日志记录器必须符合 Pino 接口; 也就是说,它必须具有以下方法:infoerrordebugfatalwarntracechild

Example:

const log = require('pino')({ level: 'info' })
const fastify = require('fastify')({ logger: log })

log.info('does not have request information')

fastify.get('/', function (req, reply) {
  req.log.info('includes request information, but is the same logger instance as `log`')
  reply.send({ hello: 'world' })
})

当前请求的日志记录器实例在生命周期的每个部分都可用。

results matching ""

    No results matching ""