hapijs / hapi-pino

🌲 Hapi plugin for the Pino logger
MIT License
148 stars 61 forks source link

Question:How to get the response body in hapi-pino logs? #121

Open veerugp opened 4 years ago

veerugp commented 4 years ago

My code is a follows:

'use strict';

const hapi = require('@hapi/hapi')
const HapiPino = require('hapi-pino')

const server = hapi.server({ port: 3000 })

server.route([
  {
    method: 'POST',
    path: '/response',
    handler:(request, h) => {
      return {'test':'Resp Msg'}
    }
  },
]);

function resSerializer(res) {
  return {
      body:res.raw.body
  };
}

(async () => {
  try {
    await server.register({
      plugin: HapiPino,
      options: {
        logPayload: true,
        serializers:{
          res: resSerializer
        },       
      }
    })
    await server.start()
    console.log('Server started successfully')
  } catch (err) {
    console.error(err)
  }
})()

Logs are as shown as below:

{"level":30,"time":1598811397374,"pid":15504,"hostname":"IN5CG7192BNG","req":{"id":"1598811397349:IN5CG7192BNG:15504:kehf0ria:10000","method":"post","url":"/response","headers":{"content-type":"application/json","user-agent":"PostmanRuntime/7.6.0","accept":"*/*","host":"localhost:3000","accept-encoding":"gzip, deflate","content-length":"50","connection":"keep-alive"},"remoteAddress":"127.0.0.1","remotePort":61801},"payload":{"test1":"JVA","test2":"JVA","test3":"JVA"},"req":{"id":"1598811397349:IN5CG7192BNG:15504:kehf0ria:10000","method":"post","url":"/response","headers":{"content-type":"application/json","user-agent":"PostmanRuntime/7.6.0","accept":"*/*","host":"localhost:3000","accept-encoding":"gzip, deflate","content-length":"50","connection":"keep-alive"},"remoteAddress":"127.0.0.1","remotePort":61801},"res":{},"responseTime":24,"msg":"request completed"}

Response body is showing as "res":{}

How to get the response body value, which is {'test':'Resp Msg'}

abeluck commented 3 years ago

The docs say this about the logPayload option:

When enabled, add the request payload as payload to the response event log.

So it seems to be to be intended that only the request payload is logged, not the response.

However I'd also like to be able to log the response payload for troubleshooting purposes, there doesn't seem to be an option for this.

SeRodrigalvarez commented 3 years ago

You can do this with a formatter:

import _ from "lodash";

const plugin = {
    plugin: require("hapi-pino"),
    options: {
        formatters: {
            log(object: any) {
                const body = _.get(object, "req.response.source");
                if (body) {
                    return {
                        ...object,
                        body,
                    };
                } else {
                    return object;
                }
            }
        }
    },
};

https://getpino.io/#/docs/api?id=formatters-object

fcesgpfedef commented 3 years ago

very helpful. Thanks