hapi.js - Logging with good and good-console

Mike Frey
InstructorMike Frey
Share this video with your friends

Social Share Links

Send Tweet

hapi doesn't ship with logging support baked in. Luckily, hapi's rich plugin ecosystem includes everything needed to configure logging for your application. This video will introduce good, a process monitor for hapi, and good-console, a reporter for good that outputs to standard out.

[00:00] Out of the box, Hapi doesn't ship with logging support beyond basic console log. If I make a request to a Hapi server, no feedback shows up in the console. Hapi does, however, have a rich ecosystem of modules and plugins that enhance Hapi in numerous ways, one of which is logging.

[00:17] I'm going to go ahead and install a couple of modules, good and good-console. Good is a process monitor for Hapi that listens for different event types, then passes those events on to reporters. Good-console is a good reporter that outputs events to standard out.

[00:33] Now that they are installed, I'll create an options object that will be used to configure good. The only required option is reporters, which is an array of objects that will configure each reporter. I'm only going to use one reporter, that's good-console. There will only be one item in my array.

[00:52] I need to tell good which event to pass on to good-console. In this case, I'm only listening for log and response event types. Next, I need to register the good plugin with my server using server.register, passing in a reference to the good module and the options I specified above.

[01:13] Server.register requires a callback as its last argument. The body of this callback is where I should complete my server setup, including defining routes and starting the server.

[01:30] Now that good is configured, let's see how it shows up in the terminal. I'll start the app and refresh the browser a few times. We now see events tagged with response coming through to the terminal.

[01:45] Speaking of tagged events, let's look at a couple of examples of how we can log tagged events. I'll add a couple of server log calls to my root route. The first argument should be a string or array of strings, each containing a tag. The second argument is the message to log. An error and info log should do.

[02:10] After restarting the server and refreshing the browser, we can see the two new events in the terminal, one tagged with error and one tagged with info. Now suppose I don't want to show log events tagged with info in my terminal.

[02:25] Instead of setting the log config to star, I can set it to an array of tags instead. Only events with those tags will be passed to the reporter. Now when I start the app and refresh the browser, only the logged events with an error tag show up.