Is there any way to turn off all console.log
statements in my JavaScript code, for testing purposes?
As far as I can tell from the documentation, Firebug doesn't supply any variable to toggle debug state. Instead, wrap console.log() in a wrapper that conditionally calls it, i.e.:
DEBUG = true; // set to false to disable debugging
function debug_log() {
if ( DEBUG ) {
console.log.apply(this, arguments);
}
}
To not have to change all the existing calls, you can use this instead:
DEBUG = true; // set to false to disable debugging
old_console_log = console.log;
console.log = function() {
if ( DEBUG ) {
old_console_log.apply(this, arguments);
}
}
If you're using gulp, then you can use this plugin:
Install this plugin with the command:
npm install gulp-remove-logging
Next, add this line to your gulpfile:
var gulp_remove_logging = require("gulp-remove-logging");
Lastly, add the configuration settings (see below) to your gulpfile.
Task Configuration
gulp.task("remove_logging", function() { return gulp.src("src/javascripts/**/*.js") .pipe( gulp_remove_logging() ) .pipe( gulp.dest( "build/javascripts/" ) ); });
Ive been using the following to deal with he problem:-
var debug = 1;
var logger = function(a,b){ if ( debug == 1 ) console.log(a, b || "");};
Set debug to 1 to enable debugging. Then use the logger function when outputting debug text. It's also set up to accept two parameters.
So, instead of
console.log("my","log");
use
logger("my","log");
My comprehensive solution to disable/override all console.*
functions is here.
Of course, please make sure you are including it after checking necessary context. For example, only including in production release, it's not bombing any other crucial components etc.
Quoting it here:
"use strict";
(() => {
var console = (window.console = window.console || {});
[
"assert", "clear", "count", "debug", "dir", "dirxml",
"error", "exception", "group", "groupCollapsed", "groupEnd",
"info", "log", "markTimeline", "profile", "profileEnd", "table",
"time", "timeEnd", "timeStamp", "trace", "warn"
].forEach(method => {
console[method] = () => {};
});
console.log("This message shouldn't be visible in console log");
})();
You could use javascript AOP (e.g. jquery-aop) to intercept all calls to console.debug/log (around) and do not proceed with the actual invocation if some global variable is set to false.
You could even do an ajax call (now and then) so you can change the log enabled/disabled behavior on the server which can be very interesting to enable debugging when facing an issue in a staging environment or such.
I developed a library for this usecase: https://github.com/sunnykgupta/jsLogger
Features:
log
, warn
, error
, info
.Is open for modifications and will be updated whenever new suggestions come up.