cylon/lib/logger.js

87 lines
2.0 KiB
JavaScript
Raw Normal View History

2013-10-25 05:25:42 +08:00
/*
* logger
* cylonjs.com
*
2015-01-08 04:58:50 +08:00
* Copyright (c) 2013-2015 The Hybrid Group
2013-10-25 05:25:42 +08:00
* 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-12-16 03:15:29 +08:00
var BasicLogger = require("./logger/basic_logger"),
NullLogger = require("./logger/null_logger"),
Config = require("./config");
2014-05-14 10:05:01 +08:00
2014-02-28 04:39:31 +08:00
// The Logger is a global object to facilitate logging stuff to the console (or
2014-12-16 03:15:29 +08:00
// other output) easily and consistently. It"s available anywhere in Cylon, as
2014-02-28 04:39:31 +08:00
// 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
2014-12-16 03:15:29 +08:00
var setLogLevel = function(level) {
var index = levels.indexOf(level),
active,
ignored;
if (index < 0) {
throw new Error("Invalid Log Level specified: " + level);
}
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() {};
});
};
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
Logger.setup = function setup(opts) {
2014-12-16 03:15:29 +08:00
var Cylon = require("./cylon");
2014-12-16 03:15:29 +08:00
if (typeof opts === "object") {
Cylon.config({ logging: opts });
}
var logger = Config.logging.logger,
level = Config.logging.level || "info";
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-12-16 03:15:29 +08:00
if (typeof level === "string") {
2014-10-27 23:59:36 +08:00
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
2014-11-06 06:24:07 +08:00
Logger.setup();