Merge pull request #235 from hybridgroup/add/log-levels

Add log levels
This commit is contained in:
Ron Evans 2014-10-28 17:38:00 +00:00
commit 903f8a9518
2 changed files with 66 additions and 6 deletions

View File

@ -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() {};
});
}

View File

@ -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');
});
});
});