我现在正在开发一个应用程序,并放置一个全局isDebug开关。我想换行console.log以方便使用。
isDebug
console.log
//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.');
然后我在 Firefox 控制台中得到这个结果。
info: Here is a msg. debug.js (line 8)
如果我想用debug()被调用的行号记录怎么办,比如info: Here is a msg. main.js (line 2)?
debug()
info: Here is a msg. main.js (line 2)
我找到了一个简单的解决方案,将接受的答案(绑定到 console.log/error/etc)与一些外部逻辑相结合,以过滤实际记录的内容。
// 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;
用法:
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
console.assert