I come from a Java background so my desire for proper unambiguous logging is strong. I prefer using the console to using some other gui widget however, in the browser I know that I can't always count on the console to exist or for it to have all the levels I might like. To remedy this I worked up the following console sanitizer and I was curious what drawbacks it might have.
function configureConsoleLog() {
"use strict";
var logMethods = [ 'trace', 'debug', 'log', 'info', 'warn', 'error' ], i;
if (!window.console) {
window.console = {log: function (args) {}}; //noop
}
for (i = 0; i < logMethods.length; i += 1) {
if (!window.console[logMethods[i]]) {
window.console[logMethods[i]] = window.console.log;
}
}
}
The idea is to find out if console exists and if it does try to find out which of the supported levels I need are available. The first level of fallback is to map unsupported methods to console.log. The second level is to create my own console variable and make a noop log function since I have nowhere to send the output. This approach leaves open the possibility of coming up with a different strategy if console doesn't exist but for now I'm content to ignore logging if there is no console.
As a side note I looked at several JS logging packages but all of them have the fatal drawback of obscuring original line numbers, usually by delegating to a console method which only reports the line number of the delegating statement.
Thoughts?