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:

logger={
    log: function(message) {
        if(window.console && console.log) console.log(message)
    },
    dir: function(message) {
        if(window.console && console.dir) console.dir(message)
    }
}

// We can call this like so:
logger.log($("head title").text());

// or so:
logger.dir($("body"));

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:

var logger = {
    logLevel: 3,
    level:{
        none: 0,
        debug : 1,
        info: 2,
        warn: 3,
        error: 4,
    },
    log: function(message) {
        if( window.console && console.log ) {
            console.log(message);
        }
    },
    debug: function(message) {
        if( window.console && console.warn
                && logger.logLevel <= logger.level.debug ) {
            console.debug(message);
        }
    },
    info: function(message) {
        if( window.console && console.warn
                && logger.logLevel <= logger.level.info ) {
            console.info(message);
        }
    },
    warn: function(message) {
        if( window.console && console.warn
                && logger.logLevel <= logger.level.warn ) {
            console.warn(message);
        }
    },
    error: function(message) {
        if( window.console && console.log
                && logger.logLevel <= logger.level.error ) {
            console.error(message);
        }
    },
    dir: function(object) {
        if( window.console && console.dir ) {
            console.dir(object);
        }
    }
};

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.

// We can now call our logging like this
logger.log("Logging level: log");
logger.debug("Logging level: debug");
logger.info("Logging level: info");
logger.warn("Logging level: warn");
logger.error("Logging level: error");

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.

shadow-left