Bunyan simple JSON logging library

Written by chamaral | Published 2018/03/28
Tech Story Tags: javascript | bunyan | logger | json-logger | json-logging-library

TLDRvia the TL;DR App

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

npm install bunyan

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.

//logger.jsvar bunyan = require('bunyan');

Then you create the logger using createLogger method.

var log = bunyan.createLogger({name: 'myapp',stream: process.stdout,level: 'info'});

log.info("This is logging");

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

{“name”:”myapp”,”hostname”:”ChamaraL”,”pid”:28027,”level”:30,”msg”:”This is logging”,”time”:”2018–03–29T15:15:33.715Z”,”v”:0}

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.

var bunyan = require('bunyan');var log = bunyan.createLogger({name: "bunyan-log",streams: [{level: 'debug',stream: process.stdout // log INFO and above to stdout},{level: 'error',path: __dirname + '/logs/appError.log' // log ERROR and above to a file}]});

module.exports = log;

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

let mongoose = require('mongoose');let config = require('./config');let logger = require('./../../utils/logger'); //path to my logger

class Database {

constructor() {  
    **this**.\_connect();  
}  

\_connect() {  
    mongoose.connect(\`mongodb://${config.server}/${config.database}\`)  
        .then(() => {  
            logger.debug('Database connection successful'); //logs the info  
        })  
        .catch(err => {  
            logger.error('Database connection error' + err); //logs the error  
        });  
}  

}

module.exports = new Database();

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


Published by HackerNoon on 2018/03/28