Bunyan simple JSON logging library

Chamara Madhushan Liyanage
HackerNoon.com
2 min readMar 29, 2018

--

Wonder how to remove console.logs in you nodeJS code. Well use a logger. The bunyan logger can simply logs messages to different streams in JSON format.

Installation

Create the logger file

After installing bunyan create a file. In my case I create a file called logger.js. First include the bunyan library.

Then you create the logger using createLogger method.

If you run this file you’ll see an output like this in you console.

Bunyan log records are JSON. A few fields are added automatically: “pid”, “hostname”, “time” and “v”.

There are several log levels defined in bunyan logging library.

  • fatal” (60): The service/app is going to stop or become unusable now. An operator should definitely look into this soon.
  • “error” (50): Fatal for a particular request, but the service/app continues servicing other requests. An operator should look at this soon(ish).
  • “warn” (40): A note on something that should probably be looked at by an operator eventually.
  • “info” (30): Detail on regular operation.
  • “debug” (20): Anything else, i.e. too verbose to be included in “info” level.
  • “trace” (10): Logging from external libraries used by your app or very detailed application logging.

Ref: https://github.com/trentm/node-bunyan#levels

You can specify the log level according to you need.

There’s a cool feature as Streams in bunyan which allows us to use different streams to log our output. Let’s say that I want to log all the errors to a external log file and the info level logs (details of operations to standard output) then we can use streams as follows.

You can defined multiple streams in the list as above. When logging level is error I save it to a file called appError.log. If the level is debug I’ve just output it in standard output.

How I’ve used the logger in my code

This way is better than writing console.log() everywhere in you code which is not a good practice.

By configuring like this you’ll get all the errors in your log file while other general outputs displayed in JSON format in the console.

If you need more details and more functionalities refer https://github.com/trentm/node-bunyan

--

--