是否有任何方法关闭我的JavaScript代码中的所有console.log语句,用于测试目的?
当前回答
你不应该!
重写内置函数不是一个好的做法。也不能保证你会抑制所有输出,你使用的其他库可能会与你的更改冲突,还有其他函数可能会写入控制台;.warning .dir (), (), . error (), .debug (), . assert()等。
正如一些人建议的那样,您可以定义一个DEBUG_MODE变量并有条件地记录日志。根据代码的复杂性和性质,编写自己的记录器对象/函数可能是一个好主意,它包装了控制台对象并内置了此功能。那将是处理仪器的正确地方。
也就是说,出于“测试”的目的,您可以编写测试,而不是打印到控制台。如果您不做任何测试,而那些console.log()行只是编写代码的辅助,那么只需删除它们。
其他回答
在脚本中重新定义console.log函数。
console.log = function() {}
够了,不再给控制台发消息了。
编辑:
扩展了Cide的想法。一个自定义记录器,您可以使用它从代码中切换登录。
从我的Firefox控制台:
var logger = function()
{
var oldConsoleLog = null;
var pub = {};
pub.enableLogger = function enableLogger()
{
if(oldConsoleLog == null)
return;
window['console']['log'] = oldConsoleLog;
};
pub.disableLogger = function disableLogger()
{
oldConsoleLog = console.log;
window['console']['log'] = function() {};
};
return pub;
}();
$(document).ready(
function()
{
console.log('hello');
logger.disableLogger();
console.log('hi', 'hiya');
console.log('this wont show up in console');
logger.enableLogger();
console.log('This will show up!');
}
);
如何使用上面的“记录器”?在就绪事件中,调用记录器。disableLogger使控制台消息不被记录。向记录器添加调用。enabllogger和logger。在希望将消息记录到控制台的方法中的disableLogger。
我之前用过温斯顿记录器。
现在,我使用以下简单的代码从经验:
从cmd/命令行设置环境变量(在Windows上): cmd setx LOG_LEVEL信息
或者,如果你愿意,你可以在你的代码中有一个变量,但上面更好。
Restart cmd/ command line, or, IDE/ editor like Netbeans Have below like code: console.debug = console.log; // define debug function console.silly = console.log; // define silly function switch (process.env.LOG_LEVEL) { case 'debug': case 'silly': // print everything break; case 'dir': case 'log': console.debug = function () {}; console.silly = function () {}; break; case 'info': console.debug = function () {}; console.silly = function () {}; console.dir = function () {}; console.log = function () {}; break; case 'trace': // similar to error, both may print stack trace/ frames case 'warn': // since warn() function is an alias for error() case 'error': console.debug = function () {}; console.silly = function () {}; console.dir = function () {}; console.log = function () {}; console.info = function () {}; break; } Now use all console.* as below: console.error(' this is a error message '); // will print console.warn(' this is a warn message '); // will print console.trace(' this is a trace message '); // will print console.info(' this is a info message '); // will print, LOG_LEVEL is set to this console.log(' this is a log message '); // will NOT print console.dir(' this is a dir message '); // will NOT print console.silly(' this is a silly message '); // will NOT print console.debug(' this is a debug message '); // will NOT print
现在,根据点1中的LOG_LEVEL设置(例如,setx LOG_LEVEL日志和重新启动命令行),上面的一些将打印,其他将不打印
希望这有帮助。
我自己弄明白后发现了这个帖子。以下是我的解决方案:
const testArray = {
a: 1,
b: 2
};
const verbose = true; //change this to false to turn off all comments
const consoleLog = (...message) => {
return verbose ? console.log(...message) : null;
};
console.log("from console.log", testArray);
consoleLog("from consoleLog", testArray);
// use consoleLog() for the comments you want to be able to toggle.
如果你使用IE7,控制台将不会被定义。所以一个更IE友好的版本是:
if (typeof console == "undefined" || typeof console.log == "undefined")
{
var console = { log: function() {} };
}
我这样写道:
//Make a copy of the old console.
var oldConsole = Object.assign({}, console);
//This function redefine the caller with the original one. (well, at least i expect this to work in chrome, not tested in others)
function setEnabled(bool) {
if (bool) {
//Rewrites the disable function with the original one.
console[this.name] = oldConsole[this.name];
//Make sure the setEnable will be callable from original one.
console[this.name].setEnabled = setEnabled;
} else {
//Rewrites the original.
var fn = function () {/*function disabled, to enable call console.fn.setEnabled(true)*/};
//Defines the name, to remember.
Object.defineProperty(fn, "name", {value: this.name});
//replace the original with the empty one.
console[this.name] = fn;
//set the enable function
console[this.name].setEnabled = setEnabled
}
}
不幸的是,它在使用严格模式下不起作用。
使用console。fn。setEnabled = setEnabled然后是console。fn。setEnabled(false) fn可以是几乎任何控制台函数。 你的情况是:
console.log.setEnabled = setEnabled;
console.log.setEnabled(false);
我还写了这个:
var FLAGS = {};
FLAGS.DEBUG = true;
FLAGS.INFO = false;
FLAGS.LOG = false;
//Adding dir, table, or other would put the setEnabled on the respective console functions.
function makeThemSwitchable(opt) {
var keysArr = Object.keys(opt);
//its better use this type of for.
for (var x = 0; x < keysArr.length; x++) {
var key = keysArr[x];
var lowerKey = key.toLowerCase();
//Only if the key exists
if (console[lowerKey]) {
//define the function
console[lowerKey].setEnabled = setEnabled;
//Make it enabled/disabled by key.
console[lowerKey].setEnabled(opt[key]);
}
}
}
//Put the set enabled function on the original console using the defined flags and set them.
makeThemSwitchable(FLAGS);
所以你只需要在FLAGS中加入默认值(在执行上面的代码之前),比如FLAGS. log = false,日志功能将在默认情况下被禁用,仍然可以调用console.log.setEnabled(true)来启用它
推荐文章
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空
- 模糊vs聚焦-有什么真正的区别吗?
- 如何使用JavaScript创建和样式一个div ?
- 清除JavaScript中的缓存
- 如何在Visual Studio中找到堆栈跟踪?
- 如何在使用Javascript替换DOM元素?
- 有一个好的Valgrind Windows的替代品吗?
- 在Redux应用程序中哪里写localStorage ?
- 如何在ReactJS中从“外部”访问组件方法?
- 为时刻添加持续时间(moment.js)
- 如何在JavaScript中获得时区名称?
- 在JSON键名中哪些字符是有效的/无效的?