Safe Cross Browser console.log in a Couple of Lines

I wanted a nice simple wrapper around console.log so that I could use it throughout my code without worrying about it choking in a particular browser. IE for example will only successfully execute console.log if you have the developer tools active. There are lots of suggestions floating around and there are also complex logging libraries like one I’ve used before with a log4j/log4net style implementation ( However, I just wanted something simple and light weight. Here is what I managed to put together based on various suggestions including a little from the YUI guys:

   var debugMode = true;

   var log = function (msg) {
       debugMode && window.console && console.log ? console.log(msg) : null;

Nice and simple. I just instrument our JS code with calls to log(“stuff”) and don’t worry about anything else. We can disable logging by flipping the debugMode flag. It will be easy to enhance the implementation later on if need be as well. One thing that I do miss that came with more complex logging implementations is a built in error threshold above which the log info will be sent to the server via an ajax call to be logged using say log4net or Nlog. I’ll probably add that at some point, having a single repository for at least all the critical log information is incredibly useful.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s