Logging Mini-Library
A mini-library that allows for extended logging inspired by the Java Logging API. The idea came as I wanted to prefix my messages to log with a timestamp. Unfortunately, Chrome prohibits the use of Function.apply and Function.call on the console.log function. This is where eval proofs that it is not necessarily evil. License: LGPL Copyright (c) Derija 2013 Germany
by Derija93
HTML
<span></span>
JavaScript
(function () {
"use strict";
/**
* @type {Object.<String, Logger>}
*/
var loggers = {},
canConsoleLog = typeof console == 'object' && typeof console.log == 'function';
/**
* Logger class
* Provides extended functionality for logging useful even without any
* console.log method available.
* @constructor
* @param {String} name The name of the Logger. Will be used to prefix logged messages.
*/
var Logger = window.Logger = function (name) {
var logs = {},
that = this;
this.logLevel = LogLevel.DEVELOP; // Log all messages by default.
(function init() {
logs[LogLevel.DEBUG] = [];
logs[LogLevel.INFO] = [];
logs[LogLevel.WARNING] = [];
logs[LogLevel.ERROR] = [];
logs[LogLevel.CRITICAL] = [];
}());
/**
* Logs one or more messages with a certain LogLevel and prints them to
* the console if available.
* @param {Number} level The LogLevel of the message(s).
* @param {...*} params Virtually infinite amount of parameters to log.
*/
this.log = function (level, params) {
if (!isCombinedLevel(level)) {
Logger.getLogger('LoggerAPI')
.debug('Can\'t log with a combined level', level);
return;
}
var time = new Date().getTime(),
logObj = {
logger: name,
time: time,
args: []
},
args = ['"[' + name + ' | ' + time + ']"'];
for (var i = 1; i < arguments.length; ++i) {
logObj.args.push(arguments[i]);
args.push('arguments[' + i + ']');
}
logs[level].push(logObj);
if (canConsoleLog && this.logLevel & level) {
eval('console.log(' + args.join(',') + ');');
}
...