Streamline Logger a bit

This commit is contained in:
Andrew Stewart 2015-01-13 10:43:20 -08:00
parent b72864ca75
commit 4b377b2e65
1 changed files with 26 additions and 64 deletions

View File

@ -12,75 +12,37 @@ var levels = ["debug", "info", "warn", "error", "fatal"];
var BasicLogger = require("./logger/basic_logger"),
NullLogger = require("./logger/null_logger"),
Config = require("./config");
Config = require("./config"),
_ = require("./lodash");
// The Logger is a global object to facilitate logging stuff to the console (or
// other output) easily and consistently. It"s available anywhere in Cylon, as
// well as in external modules that are loaded into Cylon
var Logger = module.exports = {};
var Logger = module.exports = {
setup: function(opts) {
if (typeof opts === "object") {
_.merge(Config.logging, opts);
}
var setLogLevel = function(level) {
var index = levels.indexOf(level),
active,
ignored;
var logger = Config.logging.logger,
level = Config.logging.level || "info";
if (index < 0) {
throw new Error("Invalid Log Level specified: " + level);
logger = (logger == null) ? BasicLogger : logger;
this.logger = logger || NullLogger;
this.level = level;
return this;
},
toString: function() {
return this.logger.toString();
}
active = levels.slice(index);
ignored = levels.slice(0, index);
active.forEach(function(level) {
Logger[level] = function() {
return this.logger[level].apply(this.logger, arguments);
};
});
ignored.forEach(function(level) {
Logger[level] = function() {};
});
};
// Public: Creates a Logger instance and assigns it to @logger
//
// logger - logger object to use. Defaults to a BasicLogger, or a NullLogger if
// false is supplied
//
// level - logging level to use. if supplied, will only log to specified level
// or above
//
// Returns the new logger instance
Logger.setup = function setup(opts) {
var Cylon = require("./cylon");
if (typeof opts === "object") {
Cylon.config({ logging: opts });
}
var logger = Config.logging.logger,
level = Config.logging.level || "info";
if (logger == null) { logger = BasicLogger; }
this.logger = logger || NullLogger;
if (typeof level === "string") {
setLogLevel(level);
}
return this.logger;
};
Logger.toString = function() {
return this.logger.toString();
};
levels.forEach(function(level) {
Logger[level] = function() {
return this.logger[level].apply(this.logger, arguments);
};
});
Logger.setup();
_.each(levels, function(level) {
Logger[level] = function() {
if (levels.indexOf(level) >= levels.indexOf(Logger.level)) {
return Logger.logger[level].apply(Logger.logger, arguments);
}
};
});