我现在正在开发一个应用程序,并将全局
切换。我想包装一下
以便更方便地使用。
//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)
如果我想用行号登录,该怎么办?
会被叫来,就像
发布于 2017-02-06 04:52:14
我找到了一个简单的解决方案,将接受的答案(绑定到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
请注意
使用条件日志记录。
确保浏览器的开发工具显示所有消息级别!
发布于 2015-10-04 08:21:18
这是一个古老的问题,所有提供的答案都过于hackey,存在严重的跨浏览器问题,并且没有提供任何超级有用的东西。此解决方案可在每个浏览器中运行,并完全按照其应有的方式报告所有控制台数据。不需要修改代码和一行代码
查看codepen
..。
var debug = console.log.bind(window.console)
如下所示创建交换机:
isDebug = true // toggle this to turn on / off for global controll
if (isDebug) var debug = console.log.bind(window.console)
else var debug = function(){}
然后,只需按如下方式调用:
debug('This is happening.')
您甚至可以使用如下所示的开关来接管console.log:
if (!isDebug) console.log = function(){}
如果你想用它做些有用的事情..您可以添加所有控制台方法,并将其包装在一个可重用的函数中,该函数不仅提供全局控制,而且还提供类级别的控制:
var Debugger = function(gState, klass) {
this.debug = {}
if (gState && klass.isDebug) {
for (var m in console)
if (typeof console[m] == 'function')
this.debug[m] = console[m].bind(window.console, klass.toString()+": ")
}else{
for (var m in console)
if (typeof console[m] == 'function')
this.debug[m] = function(){}
}
return this.debug
}
isDebug = true //global debug state
debug = Debugger(isDebug, this)
debug.log('Hello log!')
debug.trace('Hello trace!')
现在您可以将其添加到您的类中:
var MyClass = function() {
this.isDebug = true //local state
this.debug = Debugger(isDebug, this)
this.debug.warn('It works in classses')
}
发布于 2013-02-13 04:41:33
我喜欢
@fredrik的答案
,所以我把它卷起来
拆分Webkit堆栈跟踪的另一个答案
,并将其与
@PaulIrish的安全console.log包装器
..。“标准化”
一个“特殊的对象”,所以它很突出,在FF和Chrome中看起来几乎是一样的。
在小提琴中测试:
http://jsfiddle.net/drzaus/pWe6W/
_log = (function (undefined) {
var Log = Error; // does this do anything? proper inheritance...?
Log.prototype.write = function (args) {
///
/// Paulirish-like console.log wrapper. Includes stack trace via @fredrik SO suggestion (see remarks for sources).
///
/// list of details to log, as provided by `arguments`
/// Includes line numbers by calling Error object -- see
/// * http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
/// * https://stackoverflow.com/questions/13815640/a-proper-wrapper-for-console-log-with-correct-line-number
/// * https://stackoverflow.com/a/3806596/1037948
///
// via @fredrik SO trace suggestion; wrapping in special construct so it stands out
var suffix = {
"@": (this.lineNumber
? this.fileName + ':' + this.lineNumber + ":1" // add arbitrary column value for chrome linking
: extractLineNumberFromStack(this.stack)
)
};
args = args.concat([suffix]);
// via @paulirish console wrapper
if (console && console.log) {
if (console.log.apply) { console.log.apply(console, args); } else { console.log(args); } // nicer display in some browsers
}
};
var extractLineNumberFromStack = function (stack) {
///
/// Get the line/filename detail from a Webkit stack trace. See https://stackoverflow.com/a/3806596/1037948
///
/// the stack string
if(!stack) return '?'; // fix undefined issue reported by @sigod
// correct line number according to how Log().write implemented
var line = stack.split('\n')[2];
// fix for various display text
line = (line.indexOf(' (') >= 0
? line.split(' (')[1].substring(0, line.length - 1)
: line.split('at ')[1]
);
return line;
};
return function (params) {
///
/// Paulirish-like console.log wrapper
///
/// list your logging parameters
// only if explicitly true somewhere
if (typeof DEBUGMODE === typeof undefined || !DEBUGMODE) return;
// call handler extension which provides stack trace
Log().write(Array.prototype.slice.call(arguments, 0)); // turn into proper array
};//-- fn returned
})();//--- _log
这也适用于node,您可以使用以下命令进行测试:
// no debug mode
_log('this should not appear');
// turn it on
DEBUGMODE = true;
_log('you should', 'see this', {a:1, b:2, c:3});
console.log('--- regular log ---');
_log('you should', 'also see this', {a:4, b:8, c:16});
// turn it off
DEBUGMODE = false;
_log('disabled, should not appear');
console.log('--- regular log2 ---');
https://stackoverflow.com/questions/13815640
复制相似问题