Using Good plugin to log in Hapi

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:

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

Log to console

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

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:

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
Logging in console in Hapi

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

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

The full configuration will look like this:

Log to file

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

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

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:

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.

This logger will be send the errors, log, response objects to with certain data.

You can read more details on, about using the reporter interface.

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

If you liked this, please help spread the word by hitting the recommend button below. Thanks!