Nat*_*ins 4 javascript logging google-chrome-devtools
我目前正在使用Javascript构建一个库,并且非常喜欢Google的DevTools来进行调试.不幸的是,当我发布时,我不希望我的库记录.
这就是我的记录器当前设置的方式.
var debug = false;
var increaseSomething = function()
{
// Random Code...
if (debug) { console.log("Increased!"); }
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这非常烦人,我不应该在每次调用登录到控制台之前检查调试是否打开.
我可以尝试将控制台封装在我自己的日志记录对象中,但我觉得这不是一个好主意.有什么想法吗?
你可以这样做吗?
if (!debug) {
console.log = function() {/* No-op */}
}
Run Code Online (Sandbox Code Playgroud)
正如您所提到的,您可能不希望为所有人终止所有日志记录.这就是我经常这样做的方式.在一些实用程序文件中定义这些作为全局函数.我通常添加额外的功能LOG,WARN,ERROR和TRACE,并记录这些基于详细级别.
// Define some verbosity levels, and the current setting.
_verbosityLevels = ["TRACE", "LOG", "WARN", "ERROR"];
_verbosityCurrent = _verbosityLevels.indexOf("LOG");
// Helper function.
var checkVerbosity = function(level) {
return _verbosityLevels.indexOf(level) <= _verbosityCurrent;
}
// Internal log function.
var _log = function(msg, level) {
if(!debug && checkVerbosity(level)) console.log(msg);
}
// Default no-op logging functions.
LOG = function() {/* no-op */}
WARN = function() {/* no-op */}
// Override if console exists.
if (console && console.log) {
LOG = function(msg) {
_log(msg, "LOG");
}
WARN = function(msg) {
_log(msg, "WARN");
}
}
Run Code Online (Sandbox Code Playgroud)
这还允许您向日志添加重要信息,例如时间和呼叫者位置.
console.log(time + ", " + arguments.callee.caller.name + "(), " + msg);
Run Code Online (Sandbox Code Playgroud)
这可能会输出如下内容:
"10:24:10.123, Foo(), An error occurred in the function Foo()"
Run Code Online (Sandbox Code Playgroud)