diff --git a/lib/logger.js b/lib/logger.js index 3d3235a..51e3731 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -8,10 +8,6 @@ "use strict"; -var getArgs = function(args) { - return args.length >= 1 ? [].slice.call(args, 0) : []; -}; - var levels = ["debug", "info", "warn", "error", "fatal"]; var BasicLogger = require('./logger/basic_logger'), @@ -27,12 +23,19 @@ var Logger = module.exports = {}; // 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(logger) { +Logger.setup = function setup(logger, level) { if (logger == null) { logger = BasicLogger; } this.logger = logger || NullLogger; + if (typeof level === 'string') { + setLogLevel(level); + } + return this.logger; }; @@ -43,5 +46,28 @@ Logger.toString = function() { levels.forEach(function(level) { Logger[level] = function() { return this.logger[level].apply(this.logger, arguments); - } + }; }); + +var setLogLevel = function(level) { + var index = levels.indexOf(level), + active, + ignored; + + if (index < 0) { + throw new Error("Invalid Log Level specified"); + } + + 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() {}; + }); +} diff --git a/spec/lib/logger.spec.js b/spec/lib/logger.spec.js index 605de49..4cd2c90 100644 --- a/spec/lib/logger.spec.js +++ b/spec/lib/logger.spec.js @@ -82,4 +82,38 @@ describe('Logger', function() { }); }); }); + + describe("log levels", function() { + var logger; + + beforeEach(function() { + logger = { + debug: spy(), + info: spy(), + warn: spy(), + error: spy(), + fatal: spy() + }; + + Logger.setup(logger, 'warn'); + }); + + it("prevents logging of anything below the specified log level", function() { + Logger.debug("debug message"); + Logger.info("info message"); + + expect(logger.debug).to.not.be.called; + expect(logger.info).to.not.be.called; + }); + + it("still logs anything equal or greater than the specified log level", function() { + Logger.warn("warn message"); + Logger.error("error message"); + Logger.fatal("fatal message"); + + expect(logger.warn).to.be.calledWith('warn message'); + expect(logger.error).to.be.calledWith('error message'); + expect(logger.fatal).to.be.calledWith('fatal message'); + }); + }); });