Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change bunyan log color for different levels

When using Bunyan, all my log levels use the same cyan color, like so:

enter image description here

Here is the Bunyan configuration we are using:

const bunyan = require('bunyan');
module.exports = bunyan.createLogger({name: 'cdt-api-server'});

My question is - how can I get Bunyan to use red or magenta for logging error information / stack traces? The problem is that "ERROR" in red characters is not enough to capture my attention - I'd like to have the whole stack in red or magenta.

Here is the Bunyan readme: https://github.com/trentm/node-bunyan

I only see "color" mentioned once.

Can we do something like this?

const bunyan = require('bunyan');

module.exports = bunyan.createLogger({
  name: 'cdt-api-server',
  streams: [
    {
      level: 'trace',
      stream: process.stdout,
      color: 'black',
    },
    {
      level: 'debug',
      stream: process.stdout,
      color: 'blue',
    },
    {
      level: 'info',
      stream: process.stdout,
      color: 'cyan',
    },
    {
      level: 'error',
      path: process.stderr,
      color: 'red'
    },
    {
      level: 'warn',
      path: process.stderr,
      color: 'magenta'
    }
  ]
});
like image 549
Alexander Mills Avatar asked Aug 03 '17 22:08

Alexander Mills


2 Answers

One way to change the color of the console output when logging with bunyan is to provide a custom stream and use it in combination with the colors module.

The below example will output the info log in blue while the error log in red:

var colors = require('colors');
var bunyan = require('bunyan');

function MyRawStream() {}
MyRawStream.prototype.write = function (rec) {
    console.log('[%s] %s: %s',
        rec.time.toISOString(),
        bunyan.nameFromLevel[rec.level],
        rec.msg);
}

var log = bunyan.createLogger({
    name: 'play',
    streams: [
        {
            level: 'info',
            stream: new MyRawStream(),
            type: 'raw'
        }
    ]
});

log.info(colors.blue('This is an info message displayed in blue.'));
log.error(colors.red('This is an error message displayed in red.'));

/* Output:
[2017-08-14T20:32:33.550Z] info: This is an info message displayed in blue.
[2017-08-14T20:32:33.558Z] error: This is an error message displayed in red.
*/
like image 140
mscheker Avatar answered Nov 16 '22 21:11

mscheker


You can check how bunyan-format colors logs and do the same in your code, or just import it as a module and use it directly.

like image 43
Jehy Avatar answered Nov 16 '22 21:11

Jehy