编辑来自 pino 日志记录的请求 headers

Redact request headers from pino logging

我正在使用 koa-pino-logger,默认情况下,我会在请求完成时获得完整的请求详细信息:

req: {
  "id": 1,
  "method": "POST",
  "url": "/v1/applications/c2cc6b32-1533-4c4c-b8b6-b581855839bb/applicants",
  "headers": {
    "content-type": "application/json",
    "authorization": "Bearer eyJ0eXAiOiJK...",
    "user-agent": "PostmanRuntime/7.17.1",
    "accept": "*/*",
    "cache-control": "no-cache",
    "postman-token": "ac990b73-0eb7-4ab1-9767-6e36e96fd101",
    "host": "localhost:8080",
    "accept-encoding": "gzip, deflate",
    "content-length": "406",
    "connection": "keep-alive"
  },
  "remoteAddress": "::ffff:172.18.0.1",
  "remotePort": 54348
}
res: {
  "statusCode": 201,
  "headers": {
    "x-dns-prefetch-control": "off",
    "x-frame-options": "SAMEORIGIN",
    "strict-transport-security": "max-age=15552000; includeSubDomains",
    "x-download-options": "noopen",
    "x-content-type-options": "nosniff",
    "x-xss-protection": "1; mode=block",
    "content-type": "application/json; charset=utf-8",
    "content-length": "68"
  }
}
responseTime: 1185

我尝试使用编辑 (https://github.com/pinojs/pino/blob/master/docs/redaction.md) 删除 req.headers

import logger = require('koa-pino-logger');

const app: any = new Koa()
  .use(logger({
    redact: ['req.headers','req.headers.authorization'] // This is not working >:()
  }))
  .use(helmet())
  .use(bodyParser())
  .use(coreErrorsMiddleware)
  .use(
    oas({
      file: `${__dirname}/docs/openapi.yaml`,
      uiEndpoint: '/swagger',
      endpoint: '/openapi.json',
      errorHandler,
      validateResponse: false,
      enableUi: isDevelopmentEnvironment,
    })
  )
  .use(reload(() => import('./routes')));

这根本没有效果,但有影响的是 serializers 但是如果我尝试修改请求日志并 return 它,我会收到架构验证错误:

  .use(logger({
    serializers: {
      ["req"]: (val) => {
        // retracting req logging
        val.headers = 'redacted';
        return val
      },
    },
  }))

结果

RequestValidationError: Schema validation error

所以我现在正在使用的是通过不 return 任何东西来完全编辑 req:

  .use(logger({
    serializers: {
      ["req"]: (val) => {
        // retracting req logging
      },
    },
  }))

这导致:

我是不是用错了redact? 我可以使用其他记录器来实现我的目标吗?

我会检查您安装的 pino 版本。 redact,作为 pino 的一个特征与 v5.0.0 一起出现。如果你有一个 pino 版本 < v5.*,你需要使用 pino-noir.