diff --git a/lib/log4js.js b/lib/log4js.js index 84a7d03..3b294ab 100644 --- a/lib/log4js.js +++ b/lib/log4js.js @@ -298,13 +298,42 @@ function restoreConsole() { }); } -function loadAppender(appender) { +/** + * Load an appenderModule based on the provided appender filepath. Will first + * check if the appender path is a subpath of the log4js "lib/appenders" directory. + * If not, it will attempt to load the the appender as complete path. + * + * @param {string} appender The filepath for the appender. + * @returns {Object|null} The required appender or null if appender could not be loaded. + * @private + */ +function requireAppender(appender) { var appenderModule; try { appenderModule = require('./appenders/' + appender); } catch (e) { appenderModule = require(appender); } + return appenderModule; +} + +/** + * Load an appender. Provided the appender path to be loaded. If appenderModule is defined, + * it will be used in place of requiring the appender module. + * + * @param {string} appender The path to the appender module. + * @param {Object|void} [appenderModule] The pre-required appender module. When provided, + * instead of requiring the appender by its path, this object will be used. + * @returns {void} + * @private + */ +function loadAppender(appender, appenderModule) { + appenderModule = appenderModule || requireAppender(appender); + + if (!appenderModule) { + throw new Error("Invalid log4js appender: " + util.inspect(appender)); + } + module.exports.appenders[appender] = appenderModule.appender.bind(appenderModule); if (appenderModule.shutdown) { appenderShutdowns[appender] = appenderModule.shutdown.bind(appenderModule); diff --git a/test/configuration-test.js b/test/configuration-test.js index e198de9..ddbf7df 100644 --- a/test/configuration-test.js +++ b/test/configuration-test.js @@ -86,6 +86,21 @@ vows.describe('log4js configure').addBatch({ assert.isFunction(log4js.appenderMakers['some/other/external']); } }, + 'when appender object loaded via loadAppender': { + topic: function() { + var testAppender = makeTestAppender(), + log4js = sandbox.require('../lib/log4js'); + + log4js.loadAppender('some/other/external', testAppender); + return log4js; + }, + 'should load appender with provided object': function(log4js) { + assert.ok(log4js.appenders['some/other/external']); + }, + 'should add appender configure function to appenderMakers': function(log4js) { + assert.isFunction(log4js.appenderMakers['some/other/external']); + } + }, 'when configuration file loaded via LOG4JS_CONFIG environment variable': { topic: function() { process.env.LOG4JS_CONFIG = 'some/path/to/mylog4js.json';