Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  163] [ 7]  / answers: 1 / hits: 108959  / 12 Years ago, tue, december 11, 2012, 12:00:00

I'm developing an application and placing a global isDebug switch. I would like to wrap console.log for more convenient usage.


//isDebug controls the entire site.
var isDebug = true;

//debug.js
function debug(msg, level){
var Global = this;
if(!(Global.isDebug && Global.console && Global.console.log)){
return;
}
level = level||'info';
Global.console.log(level + ': '+ msg);
}

//main.js
debug('Here is a msg.');

Then I get this result in Firefox console.


info: Here is a msg.                       debug.js (line 8)

What if I want to log with line number where debug() gets called, like info: Here is a msg. main.js (line 2)?


More From » javascript

 Answers
19

I found a simple solution to combine the accepted answer (binding to console.log/error/etc) with some outside logic to filter what is actually logged.



// or window.log = {...}
var log = {
ASSERT: 1, ERROR: 2, WARN: 3, INFO: 4, DEBUG: 5, VERBOSE: 6,
set level(level) {
if (level >= this.ASSERT) this.a = console.assert.bind(window.console);
else this.a = function() {};
if (level >= this.ERROR) this.e = console.error.bind(window.console);
else this.e = function() {};
if (level >= this.WARN) this.w = console.warn.bind(window.console);
else this.w = function() {};
if (level >= this.INFO) this.i = console.info.bind(window.console);
else this.i = function() {};
if (level >= this.DEBUG) this.d = console.debug.bind(window.console);
else this.d = function() {};
if (level >= this.VERBOSE) this.v = console.log.bind(window.console);
else this.v = function() {};
this.loggingLevel = level;
},
get level() { return this.loggingLevel; }
};
log.level = log.DEBUG;


Usage:



log.e('Error doing the thing!', e); // console.error
log.w('Bonus feature failed to load.'); // console.warn
log.i('Signed in.'); // console.info
log.d('Is this working as expected?'); // console.debug
log.v('Old debug messages, output dominating messages'); // console.log; ignored because `log.level` is set to `DEBUG`
log.a(someVar == 2) // console.assert



  • Note that console.assert uses conditional logging.

  • Make sure your browser's dev tools shows all message levels!


[#81492] Sunday, December 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;