From 4b377b2e65a54de003445c295ce0e03863286222 Mon Sep 17 00:00:00 2001 From: Andrew Stewart Date: Tue, 13 Jan 2015 10:43:20 -0800 Subject: [PATCH] Streamline Logger a bit --- lib/logger.js | 90 +++++++++++++++------------------------------------ 1 file changed, 26 insertions(+), 64 deletions(-) diff --git a/lib/logger.js b/lib/logger.js index 62bcb66..8ff04c6 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -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); + } + }; +});