a blog for those who code

Saturday 27 December 2014

Better logging in Nodejs using Bunyan

In this post we will discuss about logging in Nodejs using Bunyan. You might have seen examples of nodejs in our site as well as in any other site, that everyone uses console.log to log the messages. Thus it gives a wrong impression to the developers that this is the best way to log messages in an application.

But, a BIGG NO to console.log. You must use something better than console.log when you are creating your node applications. In this post we will discuss about better logging in your node application by using Bunyan.

PC: https://www.npmjs.com/package/bunyan

As per Bunyan, it is a simple and fast JSON logging library for nodejs services. They also have a Bunyan CLI tool for nicely viewing the logs.

How to Install Bunyan

npm install -g bunyan // It will get you Bunyan CLI in your Path

How to Use Bunyan

Create a file named example5.js whose contents will be :

var bunyan = require('bunyan');
var log = bunyan.createLogger({name: 'myFirstBunyanExample'});
log.info('1st Log using Bunyan');
log.warn('It's just a warning');

Output Without Using CLI


Output With Using CLI



Log Levels

As you can see in the output level field is a number, where for Info it is 30 and for Warning it is 40. So, let see what are the different Log Levels available

Level Name : trace, Level Number : 10
Level Name : debug, Level Number : 20
Level Name : info, Level Number : 30
Level Name : warn, Level Number : 40
Level Name : error, Level Number : 50
Level Name : fatal, Level Number : 60

Log Method API

log.info(); // returns a boolean message to know is "info" level enabled
log.info('message'); // logs a simple message
log.info('message %s', a, b); // message formatting using util.format
log.info({a: 'b'}, 'message'); //adds "a" field to log record

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment