Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: console logging

I use console.log in my JS files to trace the application.

The problem: logs are in production environment.
How can I remove lines like console.log from code?

P.S. Please do not advice text solutions like find + xargs + grep -v.

like image 946
Dmitry Avatar asked Jun 01 '26 04:06

Dmitry


1 Answers

For my significant projects, I have my own logging function that internally uses console.log(), but there are no console.log() calls in my code except for the one place in this function. I can then enable or disable logging by changing one variable.

My function is actually a little more involved than this with options to put the output into places other than just the console, but conceptually, it looks like this:

// change this variable to false to globally turn off all logging
var myLoggingEnabled = true;   

function myLog() {
    if (myLoggingEnabled) {
        if (window.console && console.log) {
            console.log.apply(this, arguments);
        }
    }
}

You can then use code like this to log:

myLog(foo);

FYI, for deployed code compactness and performance optimization, I also have a minimization step that removes all calls to myLog() from my code. This is an optimization that I've chosen to take advantage of. Perhaps you could share why you wouldn't also consider this type of optimization.

like image 69
jfriend00 Avatar answered Jun 03 '26 19:06

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!