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

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.

Answers:

Answer

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

Answer

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
Answer

The easiest would be to use the good module with one of the good reporters, for example good-file. Here is an example how to use it:

var Hapi = require('hapi');
var Good = require('good');

var server = new Hapi.Server();
server.connection({ port: 8080 });

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        reply('Hello, world!');
    }
});

server.route({
    method: 'GET',
    path: '/{name}',
    handler: function (request, reply) {

        reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
    }
});

server.register({
    register: Good,
    options: {
        reporters: [{
            reporter: require('good-file'),
            events: {
                response: '*',
                log: '*'
            },
            config: {
                path: '/var/log/hapi',
                rotate: 'daily'
            }
        }]
    }
}, function (err) {

    if (err) {
        throw err; // something bad happened loading the plugin
    }

    server.start(function () {

        server.log('info', 'Server running at: ' + server.info.uri);
    });
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.