Wrapper for JavaScript console.log

One of the best ways to debug web applications is to use the console.log() function. The catch is while it works in Chrome as well as Firefox (with the Firebug plugin) it causes errors in IE.

Here’s my version of a very simple wrapper function which:
– Prevents errors in IE
– Supports the console functions I regularly use (log, info, warn and error)
– Allows using %s to substitute parameters. ie, log(“length is %s”, foo.length)

window.M5 = window.M5 || {};

$.each(["log","info","warn","error"], function() {
	var name = this;
	M5[name] = function () {
		if(!window.console) return; // prevents errors on IE
		console[name].apply(console, arguments);

// sample usage
M5.log("My test log message");

Note: this requires jQuery and uses the M5 namespace (which you may wish to change for your own application).

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: