cylon/lib/logger.js

74 lines
1.7 KiB
JavaScript
Raw Normal View History

2013-10-25 05:25:42 +08:00
/*
* logger
* cylonjs.com
*
* Copyright (c) 2013 The Hybrid Group
* Licensed under the Apache 2.0 license.
*/
2014-02-28 04:39:31 +08:00
"use strict";
var levels = ["debug", "info", "warn", "error", "fatal"];
2014-05-14 10:05:01 +08:00
var BasicLogger = require('./logger/basic_logger'),
NullLogger = require('./logger/null_logger');
2014-02-28 04:39:31 +08:00
// 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
2014-05-14 10:44:40 +08:00
var Logger = module.exports = {};
2014-05-14 10:05:01 +08:00
// 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
//
2014-10-27 23:59:36 +08:00
// level - logging level to use. if supplied, will only log to specified level
// or above
//
2014-05-14 10:05:01 +08:00
// Returns the new logger instance
2014-10-27 23:59:36 +08:00
Logger.setup = function setup(logger, level) {
if (logger == null) { logger = BasicLogger; }
2014-05-14 10:05:01 +08:00
this.logger = logger || NullLogger;
2013-10-25 05:25:42 +08:00
2014-10-27 23:59:36 +08:00
if (typeof level === 'string') {
setLogLevel(level);
}
2014-05-14 10:05:01 +08:00
return this.logger;
};
2013-10-25 05:25:42 +08:00
2014-05-14 10:05:01 +08:00
Logger.toString = function() {
return this.logger.toString();
};
2013-10-25 05:25:42 +08:00
levels.forEach(function(level) {
Logger[level] = function() {
return this.logger[level].apply(this.logger, arguments);
2014-10-27 23:59:36 +08:00
};
});
2014-10-27 23:59:36 +08:00
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() {};
});
}