Here's the source for a simple self-instantiating javascript logging class containing 3 logging levels.
This was a quick and dirty fix to get round the use of alert statements in my code, I've since realised that some enhancements would work well with this class, i.e. Singleton pattern and inclusion of default behaviour and styles.
/**
* Class: Logger
* Simple log output console with 3 logging levels.
* Requires prototype.js
*/
var Logger = Class.create({
LOGGER_HTML : '<div id="logger"><div id="logger-handle" class="handle"></div><div id="log_console" class="console"></div></div>',
LOG_MARKUP : '<div id="log"><h3>Log Output:</h3><ul></ul></div>',
initialize : function(config) {
config = config || {};
this._display = false;
this._level = _getLogLevel(config['level']) || 0;
this._consoleId = config['consoleId'] || 'log_console';
this._consoleWin = config['consoleWin'] || window;
this._doAlerts = config['doAlerts'] || false;
if (this._level) this._display = true;
if (this._display) $$("body")[0].insert(this.LOGGER_HTML);
},
/* Public functions */
debug : function(msg) {
if (this._level == 5) this._append("[DEBUG] " + msg);
},
info : function(msg) {
if (this._level >= 3) this._append("[INFO] " + msg);
},
error : function(msg, err) {
if (this._level >= 1) {
if (err) {
if (err.lineNumber) msg = err.lineNumber + ": " + msg + "\n";
if (err.fileName) msg = err.fileName + ": " + msg + "\n";
if (err.message) msg += " (Message: '" + err.message + "')\n";
}
this._append("[ERROR] " + msg);
}
},
/* Internals */
_append : function(msg) {
if (this._level > 0) this._doOutput(msg);
},
_doOutput : function(msg) {
if (this._doAlerts) alert(msg);
var doc = this._consoleWin.document;
var logEl = $('log');
var consoleEl = $(this._consoleId);
if (!consoleEl) {
throw "Logger instances require a DOM element to use for output.\n" +
"Please use the 'consoleId' property to specify this.";
}
if (!logEl) consoleEl.update(this.LOG_MARKUP);
var logList = consoleEl.getElementsByTagName('ul')[0];
logList.insert("" + msg + " ");
}
});
function _getLogLevel(l) {
switch (l) {
case 'debug':; case 'DEBUG': return 5; break;
case 'info':; case 'INFO': return 3; break;
case 'error':; case 'ERROR': return 1; break;
default : return 0;
}
}
/**
* Start logger using query params.
*/
document.observe("dom:loaded", function() {
var logParams = {};
if (location.search.indexOf("showLog=true") > -1) {
// Append ?showLog=true&level=debug for debug level logger.
logParams = location.search.toQueryParams();
}
logger = new Logger(logParams);
if (typeof Draggable != 'undefined') new Draggable('logger', {handle: 'logger-handle'});
});
blog comments powered by Disqus