I'd like to see a nice log with short info about each request to my server, for use during development. I've seen the documentation on http://hapijs.com/api#request-logs, but I couldn't understand enough of it to get it working.
What should I pass as the config
object when I create the server? Should I then listen to events and log them or does it happen automatically? How do I log all the requests, and not just the errors?
I'd like to avoid installing logging libraries.
When defining a route in hapi, you need three basic elements: the path, the method, and a handler. These are passed to your server as an object, and can be as simple as the following: server.route({ method: 'GET', path: '/', handler: function (request, h) { return 'Hello World!'; } });
Correctly Stop Your hapi Server At the moment you receive a SIGINT in your application you can use hapi's server. stop() method which waits for open connections to be processed and shuts down afterwards.
So I found a way:
server.events.on('response', function (request) {
console.log(request.info.remoteAddress + ': ' + request.method.toUpperCase() + ' ' + request.path + ' --> ' + request.response.statusCode);
});
The log then looks like this:
127.0.0.1: GET /myEndpoint/1324134?foo=bar --> 200
127.0.0.1: GET /sgsdfgsdrh --> 404
Answer edited for Hapi v18, see older versions here
In Hapi.js version above v17, please make the below changes to make it work:
server.events.on('response', function (request) {
// you can use request.log or server.log it's depends
server.log(request.info.remoteAddress + ': ' + request.method.toUpperCase() + ' ' + request.url.path + ' --> ' + request.response.statusCode);
});
The log will be:
127.0.0.1: GET /todo --> 200
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With