Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log all requests made to a hapi server without using a logging library?

Tags:

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.

like image 992
mik01aj Avatar asked Apr 20 '15 11:04

mik01aj


People also ask

What is Hapi H?

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!'; } });

How do I cancel my Hapi server?

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.


2 Answers

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

like image 140
mik01aj Avatar answered Oct 04 '22 15:10

mik01aj


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
like image 26
Vipin Avatar answered Oct 04 '22 14:10

Vipin