Skip to content
Robert edited this page Aug 16, 2016 · 1 revision

Welcome to the loglevel wiki!

LogLevel Plugins

I created a simple and small plugin that enables colorful log output via ANSI escape codes. It depends on the "chalk" library.

var log = require('loglevel');
var chalk = require('chalk');

// very simple quick'n'dirty hash function
var getColorFromStr = function(str) {
  if (str === undefined || str.length == 0) return chalk.white
  var hash = 0, i, len;
  for (var i = str.length; i--; ) {
    hash += str.charCodeAt(i);
  }
  var chalkColors = [ chalk.red, chalk.green, chalk.yellow, chalk.blue, chalk.magenta, chalk.cyan]
  return chalkColors[ hash % chalkColors.length ]
};

// loglevel Plugin to create colorfull log output using 'chalk'
var originalFactory = log.methodFactory;
log.methodFactory = function (methodName, logLevel, loggerName) {
    var rawMethod = originalFactory(methodName, logLevel, loggerName);
    var logLevelNames = ['TRACE', 'DEBUG', 'INFO ', 'WARN ', 'ERROR'];
    var messageColor  = getColorFromStr(loggerName);  // or getColorFromStr(logLevel)

    return function (message) {
      rawMethod(chalk.cyan.underline(loggerName) + " " +
                chalk.bold.magenta(logLevelNames[logLevel]) + " " +
                messageColor(message) );
    };
};
log.setLevel("trace");  // must setLevel to activate plugin
Clone this wiki locally