记录 Fastify 响应体

Logging Fastify response body

如何 log Fastify 中的响应主体?正文似乎没有作为响应对象的一部分公开:

const fastify = require('fastify')({
  logger: {
    serializers: {
      res: function (res) { 
        // No body in req afaik
        return {  } 
      }
    }
  }
})

这是一个工作示例。我认为这种用法只需要用于调试,因为如果你有很多 req/sec.

,你就会变慢

我还添加了一个 JSON 模式验证作为演示:

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

fastify.register(async function (fastify, opts) {
  fastify.addHook('onSend', function (request, reply, payload, next) {
    console.log(payload);
    next()
  })

  fastify.get('/', {
    schema: {
      response: {
        '2xx': { properties: { this: { type: 'string' } } }
      }
    }
  }, async function () {
    return { this: 'is', a: 'json' }
  })
})

fastify.listen(3000)

您将获得:

curl http://localhost:3000/

{"this":"is"}

试试这个:

const fastify = require('fastify')({
  logger: {
    serializers: {
      res: function (res) {
        return {
          statusCode: res.statusCode,
          payload: res.payload,
        }
      },
    }
  }
})

fastify.addHook('onSend', function (_request, reply, payload, next) {
  Object.assign(reply.res, { payload });
  next();
})

如果您的一些有效载荷是对象,并且您希望在它们被序列化之前将它们序列化 - 好吧,序列化 - 您也可以添加 preSerialization 挂钩:

fastify
  .addHook('preSerialization', (_request, reply, payload, next) => {
    Object.assign(reply.res, { payload });
    next();
  })
  .addHook('onSend', (_request, reply, payload, next) => {
    if (!reply.res.payload) Object.assign(reply.res, { payload });
    next();
  });