Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging request and response payloads in Hapi.js using Good

I am using Hapi.js to implement RESTful API for my mobile application. I have integrated Good for logging requests, errors, and other events. It works very well for me. However it is not clear how to log request and response payloads (JSON objects).

I would appreciate any help.

like image 490
Jeltok Avatar asked Aug 26 '14 19:08

Jeltok


2 Answers

This logs what you need:

server.on('response', function (request) {
    console.log(request.info.remoteAddress + ': ' + request.method.toUpperCase() + ' ' + request.url.path + ' --> ' + request.response.statusCode);
    console.log('Request payload:', request.payload);
    console.log('Response payload:', request.response.source);
});

I haven't used Good, but I guess that connecting this to Good shouldn't be hard.

like image 194
mik01aj Avatar answered Nov 08 '22 20:11

mik01aj


I know this is late but it's worth putting here that you can now optionally capture request and response payloads with good:

[requestPayload] - determines if the request payload will be available to reporter objects. Defaults to false

[responsePayload] - determines if the response payload will be available to reporter objects. Defaults to false

For example:

var options = {
    responsePayload: true,
    reporters: [{
        reporter: require('good-console'),
        events: { log: '*', response: '*' }
    }]
};

Something to be careful of is that you will more than likely now be storing username and passwords in plain text in your log files. You should consider using the filter option when logging response and request payloads:

[filter] - an object with the following keys:

  • key - the key of the data property to change
  • value - a string that can be one of the following:
    • "censor" - replace the text with "X"s
    • "remove" - deletes the value a valid regular express string. Only supports a single group. Ex: "(\d{4})$" will replace the last four digits with "X"s. Take extra care when creating this string. You will need to make sure that the resultant RegExp object is what you need.
like image 25
Clarkie Avatar answered Nov 08 '22 20:11

Clarkie