Structured logging in Node.js with Bunyan and Seq

Bunyan is a structured logging library for Node.js. From the README:

Manifesto: Server logs should be structured. JSON's a good format. Let's do that. […]

We agree! Though Seq is used most widely with .NET apps, it’s also nicely matched with Bunyan. We’ll be officially supporting it through the bunyan-seq package that’s now on NPM.

Here’s how to get started.

Installing from NPM

To log to Seq from Node.js, you’ll need both the bunyan and seq-bunyan packages:

npm install --save bunyan
npm install --save bunyan-seq

Configuring the logger

To log events through Bunyan, first create a logger object. The constructor API accepts an array of “streams”, which are destinations for log events.

let bunyan = require('bunyan');
let seq = require('bunyan-seq');

var log = bunyan.createLogger({
    name: 'myapp',
    streams: [
        seq.createStream({serverUrl: 'http://localhost:5341'})
    ]
});

Notice that the logger is given a name. This will be attached to all events as a property – generally this will be the name of the application or service.

The Seq createStream() method accepts the URL of the Seq server, optionally an apiKey, and a bunch of other parameters that control how events are bundled into batches.

Writing events

Bunyan has a nice predictable logging API that should feel familiar:

log.info('Hi!');
log.warn({lang: 'fr'}, 'Au revoir');

In the second line, {lang: 'fr'} is an object with additional structured data to associate with the event. In Seq the fields of this object will be displayed as properties.

Bunyan Events in Seq

Finding events by property is easy by querying Seq with lang == "fr" and so-on.

Rendering with message templates

JSON is a great format for machine-readable logs, but human-readability can suffer when there are many properties to visually scan.

To fix this, Seq uses the message template syntax to format properties into the log message.

log.info({user: r.username, device: r.device},
         'Sign-in from {user} on {device}');

The included properties are intelligently rendered in the Seq UI.

Bunyan with Message Templates

While message templates aren’t rendered by other Bunyan streams, the default behavior of printing the template plus properties is a nice fallback that still adds some additional semantic content to the event.

Roadmap

The bunyan-seq package is our first supported client for Node.js and while it's pre-1.0 we need your help to put it through its paces. Your feedback, suggestions and bug reports are welcome here or on the GitHub project site.

The underlying Seq client library for Node.js is designed to be used independently of Bunyan, so if you're using Node.js with an alternative logging library we'd also love to hear from you.

Happy (Node.js) logging!

Nicholas Blumhardt

Read more posts by this author.