You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Fastify默认Pino日志中移除hostname字段?

移除Fastify默认日志中的hostname字段

Fastify默认基于Pino实现日志功能,要移除日志中的hostname字段,可通过以下两种方式实现,同时解决TypeScript类型兼容问题:

方法1:利用Pino的base选项

Pino的base配置项可控制默认注入的字段,将hostname设为undefined即可让Pino不再输出该字段:

JavaScript 实现

const fastify = require('fastify')({
  logger: {
    base: { hostname: undefined }
  }
})

fastify.get('/', async (req) => {
  req.log.info('请求处理完成')
  return { status: 'ok' }
})

fastify.listen({ port: 3000 }, err => {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

TypeScript 实现(类型断言)

由于FastifyLoggerOptions未包含base字段,可通过类型断言绕过类型检查:

import fastify from 'fastify'

const app = fastify({
  logger: {
    base: { hostname: undefined }
  } as unknown as fastify.FastifyLoggerOptions
})

app.get('/', async (req) => {
  req.log.info('TypeScript 请求处理')
  return { status: 'ok' }
})

app.listen({ port: 3000 }, err => {
  if (err) {
    app.log.error(err)
    process.exit(1)
  }
})

TypeScript 实现(扩展类型)

若想避免类型断言,可扩展FastifyLoggerOptions类型:

import fastify, { FastifyLoggerOptions } from 'fastify'

interface CustomLoggerOpts extends FastifyLoggerOptions {
  base?: { hostname?: string | undefined; pid?: number | undefined }
}

const app = fastify({
  logger: { base: { hostname: undefined } } as CustomLoggerOpts
})

// 业务代码同上

方法2:使用Pino的redact选项

redact可直接从日志输出中移除指定字段,实现更简单:

const fastify = require('fastify')({
  logger: { redact: ['hostname'] }
})

TypeScript环境下同样可通过类型断言或扩展类型解决类型问题。

效果验证

配置后日志输出示例:

{"level":30,"time":1660583707685,"pid":17,"msg":"Server listening at http://0.0.0.0:80"}

hostname字段已被移除。


内容的提问来源于stack exchange,提问作者Paymahn Moghadasian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:27:31