log4js-node/lib/logger.js

81 lines
2.1 KiB
JavaScript
Raw Normal View History

2013-05-30 06:26:26 +08:00
"use strict";
var debug = require('./debug')('logger')
, levels = require('./levels')
2013-05-30 06:26:26 +08:00
, util = require('util')
, DEFAULT_CATEGORY = '[default]';
/**
* Models a logging event.
* @constructor
* @param {String} categoryName name of category
* @param {Log4js.Level} level level of message
* @param {Array} data objects to log
* @author Seth Chisamore
*/
function LoggingEvent (categoryName, level, data) {
2013-05-30 06:26:26 +08:00
this.startTime = new Date();
this.categoryName = categoryName;
this.data = data;
this.level = level;
}
/**
* Logger to log messages.
* use {@see Log4js#getLogger(String)} to get an instance.
* @constructor
* @param name name of category to log to
* @author Stephan Strittmatter
*/
function Logger (name, level, dispatch) {
2013-05-30 06:26:26 +08:00
this.category = name || DEFAULT_CATEGORY;
if (level) {
this.setLevel(level);
}
this.dispatch = dispatch;
}
Logger.DEFAULT_CATEGORY = DEFAULT_CATEGORY;
2013-05-30 06:26:26 +08:00
Logger.prototype.level = levels.TRACE;
Logger.prototype.setLevel = function(level) {
debug("setting level to " + level);
2013-05-30 06:26:26 +08:00
this.level = levels.toLevel(level, this.level || levels.TRACE);
};
Logger.prototype.removeLevel = function() {
2013-05-30 06:26:26 +08:00
delete this.level;
};
Logger.prototype.log = function() {
2013-05-30 06:26:26 +08:00
var args = Array.prototype.slice.call(arguments)
, logLevel = args.shift()
, loggingEvent = new LoggingEvent(this.category, logLevel, args);
debug("Logging event " + loggingEvent + " to dispatch = " + util.inspect(this.dispatch));
this.dispatch(loggingEvent);
};
Logger.prototype.isLevelEnabled = function(otherLevel) {
2013-05-30 06:26:26 +08:00
return this.level.isLessThanOrEqualTo(otherLevel);
};
['Trace','Debug','Info','Warn','Error','Fatal'].forEach(
2013-05-30 06:26:26 +08:00
function(levelString) {
var level = levels.toLevel(levelString);
Logger.prototype['is'+levelString+'Enabled'] = function() {
return this.isLevelEnabled(level);
};
Logger.prototype[levelString.toLowerCase()] = function () {
if (this.isLevelEnabled(level)) {
var args = Array.prototype.slice.call(arguments);
args.unshift(level);
Logger.prototype.log.apply(this, args);
}
};
}
);
exports.LoggingEvent = LoggingEvent;
exports.Logger = Logger;