Skip to content

Instantly share code, notes, and snippets.

@solendil
Last active February 10, 2022 18:57
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save solendil/412d09202cea7b4544dcc57114c1151a to your computer and use it in GitHub Desktop.
A simple Javascript logger with modules and levels that preserves line numbers
/*
* Copyright 2016, Matthieu Dumas
* This work is licensed under the Creative Commons Attribution 4.0 International License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/
*/
/* Usage :
* var log = Logger.get("myModule") // .level(Logger.ALL) implicit
* log.info("always a string as first argument", then, other, stuff)
* log.level(Logger.WARN) // or ALL, DEBUG, INFO, WARN, ERROR, OFF
* log.debug("does not show")
* log("but this does because direct call on logger is not filtered by level")
*/
var Logger = (function() {
var levels = {
ALL:100,
DEBUG:100,
INFO:200,
WARN:300,
ERROR:400,
OFF:500
};
var loggerCache = {};
var cons = window.console;
var noop = function() {};
var level = function(level) {
this.error = level<=levels.ERROR ? cons.error.bind(cons, "["+this.id+"] - ERROR - %s") : noop;
this.warn = level<=levels.WARN ? cons.warn.bind(cons, "["+this.id+"] - WARN - %s") : noop;
this.info = level<=levels.INFO ? cons.info.bind(cons, "["+this.id+"] - INFO - %s") : noop;
this.debug = level<=levels.DEBUG ? cons.log.bind(cons, "["+this.id+"] - DEBUG - %s") : noop;
this.log = cons.log.bind(cons, "["+this.id+"] %s");
return this;
};
levels.get = function(id) {
var res = loggerCache[id];
if (!res) {
var ctx = {id:id,level:level}; // create a context
ctx.level(Logger.ALL); // apply level
res = ctx.log; // extract the log function, copy context to it and returns it
for (var prop in ctx)
res[prop] = ctx[prop];
loggerCache[id] = res;
}
return res;
};
return levels; // return levels augmented with "get"
})();
// should show numbers 1 to 17 and never show "---- ERROR"
var log = Logger.get("first"); // do all levels work
log.log("1");
log.debug("2");
log.info("3");
log.warn("4");
log.error("5");
log("6");
log.level(Logger.INFO); // do all levels work after a level change
var log2 = Logger.get("second").level(Logger.WARN); // and when a second logger is in the mix ?
log.log("7");
log.debug("---- ERROR");
log2.log("8");
log2.debug("---- ERROR");
log2.info("---- ERROR");
log.info("9");
log.warn("10");
log.error("11");
log("12");
log2.warn("13");
log2.error("14");
log2("15");
var log = Logger.get("first"); // do we get the cached logger with its config?
log.debug("---- ERROR");
log.error("16");
log("17");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment