Using Good plugin to log in Hapi


hapi nodejs Tutorials

To add logging in our Hapi-based application we will use a good-plugin. It’s official plugin from Hapi plugins ecosystem. Good plugin used to report and monitor Hapi server events. In this tutorial, I want to show you how to log to file, to console and to API-endpoints using good-plugin.

Getting started

Let’s go to an existing Hapi project folder and create our server file:

'use strict';

const Hapi = require('hapi');

const server = Hapi.server({
    port: 3000,
    host: 'localhost'
});

server.route({
    method: 'GET',
    path: '/index',
    handler: (request, h) => {
        return h.response('index');
    }
});

server.route({
    method: 'GET',
    path: '/about',
    handler: (request, h) => {
        return h.response('about');
    }
});

const init = async () => {
    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

We can install the good and good-squeeze plugins using the following in the terminal:

npm i good good-console -s

Log to console

Let’s create an options object, where we will set the interval of logging and how we will log:

const options = {
    ops: {
        interval: 1000
    },
    reporters: {
        console: [{
            module: 'good-console'
        }, 'stdout']
    }
};

Every second we will log information about our server status and i/o requests, responses to terminal console. But at the beginning, we have to register the Good plugin and options configuration, before our server starts:

await server.register({
    plugin: require('good'),
    options
});

When you run the server and make some requests to /index or /about route, you should see the next in console:

Loggin in console in Hapi

If we need only to log and response events, we should install the good-squeeze plugin:

npm i good-squeeze -s

And push the next object to options.reporters.console array:

{
    module: 'good-squeeze',
    name: 'Squeeze',
    args: [{
        log: '*',
        response: '*'
    }]
}

The full configuration will look like this:

reporters: {
    console: [{
            module: 'good-squeeze',
            name: 'Squeeze',
            args: [{
                log: '*',
                response: '*'
            }]
        },
        {
            module: 'good-console'
        }, 'stdout'
    ]
}

Log to file

To save logs to file we should install the another Good plugin - good-file:

npm i good-file -s

To save every request and response log we can use the next configuration:

reporters: {
    file: [{
        module: 'good-squeeze',
        name: 'Squeeze',
        args: [{
            log: '*',
            response: '*'
        }]
    }, {
        module: 'good-squeeze',
        name: 'SafeJson'
    }, {
        module: 'good-file',
        args: ['./logs/server_log']
    }]
}

Every request log or response log object will be saved to ./logs/server_log file.

Log to another API-endpoint

To logging to another API-endpoint, we should install the good-http plugin:

npm i good-http -s

We can use the following configuration inside options object, if we want to stream logs to another API endpoint. It’s very useful for debugging.

reporters: {
    http: [{
        module: 'good-squeeze',
        name: 'Squeeze',
        args: [{error: '*', log: '*', response: '*'}]
    }, {
        module: 'good-http',
        args: [
            'http://production.somesite.com:5000',
            {
                wreck: {
                    headers: {
                        'x-logger': 'mobile'
                    }
                }
            }
        ]
    }]
}

This logger will be send the errors, log, response objects to http://production.somesite.com:5000 with certain data.

You can read more details on https://github.com/hapijs/good/blob/master/API.md#reporter-interface, about using the reporter interface.

Learning Hapi.js? Buy my Hapi.js Handbook🔥

comments powered by Disqus