Skip to content

Instantly share code, notes, and snippets.

@lamchau
Created April 21, 2015 00:31
Show Gist options
  • Save lamchau/44365f575857789613bd to your computer and use it in GitHub Desktop.
Save lamchau/44365f575857789613bd to your computer and use it in GitHub Desktop.
simple pretty log4j-like logging (requires chalk for color)
var util = require('util');
var chalk = require('chalk');
var LOG_TYPE = chalk.bold.black('[') + '%s' + chalk.bold.black(']') + ':';
var ALL = {
type: 'ALL'
};
var TRACE = {
type: 'TRACE',
fn: console.log,
get prefix() {
return util.format(LOG_TYPE, chalk.bold.white(this.type));
},
};
var DEBUG = {
type: 'DEBUG',
fn: console.log,
get prefix() {
return util.format(LOG_TYPE, chalk.white(this.type));
},
};
var INFO = {
type: 'INFO',
fn: console.info,
get prefix() {
return util.format(LOG_TYPE, chalk.bold.cyan(' ' + this.type));
}
};
var WARN = {
type: 'WARN',
fn: console.warn,
get prefix() {
return util.format(LOG_TYPE, chalk.bold.yellow(' ' + this.type));
}
};
var ERROR = {
type: 'ERROR',
fn: console.error,
get prefix() {
return util.format(LOG_TYPE, chalk.bold.red(this.type));
}
};
var FATAL = {
type: 'FATAL',
fn: console.error,
get prefix() {
return util.format(LOG_TYPE, chalk.bold.white.bgRed(this.type));
}
};
var OFF = {
type: 'OFF'
};
var LEVELS = [
ALL,
TRACE,
DEBUG,
INFO,
WARN,
ERROR,
FATAL,
OFF
].reduce(indexByType, {});
var priority = ALL.priority;
function indexByType(map, value, index) {
map[value.type] = value;
value.priority = Math.pow(2, index);
return map;
}
function log(level, args) {
if (level.priority < priority || typeof level.fn !== 'function') {
return;
}
args = [].slice.call(args);
args.unshift(level.prefix);
level.fn.apply(console, args);
}
function debug() {
log(DEBUG, arguments);
}
function disable() {
priority = OFF.priority;
}
function enable() {
priority = ALL.priority;
}
function error() {
log(ERROR, arguments);
}
function info() {
log(INFO, arguments);
}
function warn() {
log(WARN, arguments);
}
function setLevel(level) {
if (level > 0 && ((level & (level - 1)) === 0)) {
priority = level;
} else {
level = String(level).trim().toUpperCase();
if (LEVELS[level]) {
priority = LEVELS[level].priority;
}
}
}
module.exports = {
debug: debug,
disable: disable,
enable: enable,
error: error,
info: info,
setLevel: setLevel,
warn: warn
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment