Writing on the principles & practice of building digital products

A better console log

Write yourself a custom console log wrapper for control, brevity and nerd points.

If you do any amount of work with Javascript, logging messages to the console will be familiar to you. Remembering to remove aforementioned logs when going to production and indeed having to repeatedly type console.log are both a pain. A neat way to get around this is to write a custom wrapper which does your logging for you, giving you control and brevity in one fell swoop. So without further ado, here's what I use:

// Custom console log wrapper
// 
// Usage: l('message');
// 
// To turn logging on with: 
// localStorage.setItem('debug', true);
// 
// Turn logging off with: 
// localStorage.setItem('debug', false);

window.l = function(message) {
  if (typeof console != 'undefined') {
    if (localStorage.getItem('debug') == 'true') {
      console.log(message);
    }
  }
}

So now, instead of having to write the unbelievably tedious:

console.log('message');

We can write the infinitely more suave:

l('message');

Pretty sweet. All you need to do is include the above function, set localStorage.setItem('debug', true) in your browser and you're cooking with gas.