JavaScript: console logging (with IE safety)

Every once in a while I work on a site which has some or copious amounts of javascript. Now I do not mind this at all. But it’s pretty tedious stuff writing the code and putting in loggers. And when you’re working on something and you have to test it on IE. Well let’s just say the console may cause some problems.

But rather then removing all the logging i’ve found there’s an easy solution. Building yourself a logger like structure which checks the existence of the console before writing. That way you can add logging statements without crashing the entire application. A sample logger would look like this:

This negates the IE error’s when calling console directly. Now if we want to be able to set the log level we can extend our logger with a level like so:

This enables us to call the logging on several levels and easily set the loglevel for the entire project. But note that the above structure always shows log and dir. I keep it this way because I think these are best left for development purposes.

Of course there are many ways to enhance this even further. But for now I hope this post has given you some usefull information and solutions for console logging over browsers.

Leave a Reply

Your email address will not be published. Required fields are marked *