Monday, July 2, 2018

A proper wrapper for console.log with correct line number?

While writing a simple JavaScript 'class', I wanted to toggle console.logs on for development and off for production.  Normally I would create a method to wrap console.log with a debug flag, such as:

function Awesome() {
   this.debug = true;

   this.log = function(msg) {
       if (this.debug) {
           console.log(msg);    // line 6
       }
   };
   
   this.log('test');            // outputs line 6
   
   this.doStuff = function() {
       this.log('doing stuff'); // outputs line 6
   };
}

But the line number logged is always from within the log wrapper, this.log(),
which is not overly useful.
After some searching, I ran across this StackOverflow thread
Basically, instead of using a logging wrapper, use a function alias.

function Awesome() {
   this.debug = true;
   
   if (this.debug && window.console && console.log && console.warn && console.error) {
       this.console = {
           'log': window.console.log,
           'warn': window.console.warn,
           'error': window.console.error
       };
   } else {
       this.console = {
           'log': function(){},
           'warn': function(){},
           'error': function(){}
       };
   }
   
   this.console.log('test');            // outputs line 18
   
   this.doStuff = function() {
       this.console.log('doing stuff'); // outputs line 21
   };
}    

So now Awesome is awesome with logging showing the original line number,
which is helpful for debugging.

Of course, this.console could be renamed to anything, such as this.log, this.out, etc.
And you could add the log to the window namespace so it could be used by other functions, such as window.debug or window.log, etc

End of document. Thanks for reading.

No comments:

Post a Comment