From 276d89319898e7fd31c1c25c66557401b438296a Mon Sep 17 00:00:00 2001 From: Scott Yoshizawa Date: Thu, 30 Apr 2015 17:01:22 -0400 Subject: [PATCH] Added the capability to register custom loggers (for Issue #626) --- red/log.js | 46 ++++++++++++++++++++++++++++++-------------- test/red/log_spec.js | 16 +++++++++++++++ 2 files changed, 48 insertions(+), 14 deletions(-) diff --git a/red/log.js b/red/log.js index f41ce4fb3..d3160e228 100644 --- a/red/log.js +++ b/red/log.js @@ -42,26 +42,36 @@ var logHandlers = []; var metricsEnabled = false; -var ConsoleLogHandler = function(settings) { - this.logLevel = levels[settings.level]||levels.info; - this.metricsOn = settings.metrics||false; +var LogHandler = function(settings) { + this.logLevel = settings ? levels[settings.level]||levels.info : levels.info; + this.metricsOn = settings ? settings.metrics||false : false; metricsEnabled = this.metricsOn; + this.handler = (settings && settings.handler) ? settings.handler(settings) : consoleLogger; + //if (settings && settings.handler) { + //this.handler = settings.handler(settings); + //} else { + //this.handler = consoleLogger; + //} this.on("log",function(msg) { if (this.shouldReportMessage(msg.level)) { - if (msg.level == log.METRIC) { - util.log("[metric] "+JSON.stringify(msg)); - } else { - util.log("["+levelNames[msg.level]+"] "+(msg.type?"["+msg.type+":"+(msg.name||msg.id)+"] ":"")+msg.msg); - } + this.handler(msg); } }); } -util.inherits(ConsoleLogHandler, EventEmitter); +util.inherits(LogHandler, EventEmitter); -ConsoleLogHandler.prototype.shouldReportMessage = function(msglevel) { +LogHandler.prototype.shouldReportMessage = function(msglevel) { return msglevel <= this.logLevel || (msglevel == log.METRIC && this.metricsOn); } +var consoleLogger = function(msg) { + if (msg.level == log.METRIC) { + util.log("[metric] "+JSON.stringify(msg)); + } else { + util.log("["+levelNames[msg.level]+"] "+(msg.type?"["+msg.type+":"+(msg.name||msg.id)+"] ":"")+msg.msg); + } +} + var log = module.exports = { FATAL: 10, ERROR: 20, @@ -73,11 +83,19 @@ var log = module.exports = { init: function(settings) { logHandlers = []; - var consoleSettings = {}; - if (settings.logging) { - consoleSettings = settings.logging.console || {}; + var loggerSettings = {}; + var keys = Object.keys(settings.logging); + if (keys.length === 0) { + log.addHandler(new LogHandler()); + } else { + for (var i=0, l=keys.length; i