changed config loading to be more predictable

This commit is contained in:
Gareth Jones 2012-05-29 15:50:35 +10:00
parent ccc4976206
commit 754ac2c5ac
2 changed files with 50 additions and 85 deletions

View File

@ -55,7 +55,13 @@ var events = require('events')
, ALL_CATEGORIES = '[all]' , ALL_CATEGORIES = '[all]'
, appenders = {} , appenders = {}
, loggers = {} , loggers = {}
, appenderMakers = {}; , appenderMakers = {}
, defaultConfig = {
appenders: [
{ type: "console" }
],
replaceConsole: false
};
/** /**
* Get a logger instance. Instance is cached on categoryName level. * Get a logger instance. Instance is cached on categoryName level.
@ -146,8 +152,6 @@ function configureAppenders(appenderList) {
throw new Error("log4js configuration problem for "+util.inspect(appenderConfig)); throw new Error("log4js configuration problem for "+util.inspect(appenderConfig));
} }
}); });
} else {
addAppender(consoleAppender());
} }
} }
@ -243,22 +247,9 @@ function getDefaultLogger () {
return getLogger(DEFAULT_CATEGORY); return getLogger(DEFAULT_CATEGORY);
} }
function findConfiguration(filename) {
var path;
try {
path = require.resolve(filename || 'log4js.json');
} catch (e) {
//file not found. default to the one in the log4js module.
path = filename || __dirname + '/log4js.json';
}
return path;
}
var configState = {}; var configState = {};
function loadConfigurationFile(filename) { function loadConfigurationFile(filename) {
filename = findConfiguration(filename);
if (filename && (!configState.lastFilename || filename !== configState.lastFilename || if (filename && (!configState.lastFilename || filename !== configState.lastFilename ||
!configState.lastMTime || fs.statSync(filename).mtime !== configState.lastMTime)) { !configState.lastMTime || fs.statSync(filename).mtime !== configState.lastMTime)) {
configState.lastFilename = filename; configState.lastFilename = filename;
@ -274,10 +265,10 @@ function configureOnceOff(config) {
configureAppenders(config.appenders); configureAppenders(config.appenders);
configureLevels(config.levels); configureLevels(config.levels);
if (config.doNotReplaceConsole) { if (config.replaceConsole) {
restoreConsole();
} else {
replaceConsole(); replaceConsole();
} else {
restoreConsole();
} }
} catch (e) { } catch (e) {
throw new Error("Problem reading log4js config " + util.inspect(config) + ". Error was \"" + e.message + "\" ("+e.stack+")"); throw new Error("Problem reading log4js config " + util.inspect(config) + ". Error was \"" + e.message + "\" ("+e.stack+")");
@ -286,7 +277,7 @@ function configureOnceOff(config) {
} }
function reloadConfiguration() { function reloadConfiguration() {
var filename = findConfiguration(configState.filename), var filename = configState.filename,
mtime; mtime;
if (!filename) { if (!filename) {
// can't find anything to reload // can't find anything to reload
@ -316,7 +307,7 @@ function initReloadConfiguration(filename, options) {
configState.timerId = setInterval(reloadConfiguration, options.reloadSecs*1000); configState.timerId = setInterval(reloadConfiguration, options.reloadSecs*1000);
} }
function configure (configurationFileOrObject, options) { function configure(configurationFileOrObject, options) {
var config = configurationFileOrObject; var config = configurationFileOrObject;
options = options || {}; options = options || {};
@ -324,7 +315,7 @@ function configure (configurationFileOrObject, options) {
if (options.reloadSecs) { if (options.reloadSecs) {
initReloadConfiguration(config, options); initReloadConfiguration(config, options);
} }
config = loadConfigurationFile(config); config = loadConfigurationFile(config) || defaultConfig;
} else { } else {
if (options.reloadSecs) { if (options.reloadSecs) {
getLogger('log4js').warn('Ignoring configuration reload parameter for "object" configuration.'); getLogger('log4js').warn('Ignoring configuration reload parameter for "object" configuration.');
@ -332,7 +323,7 @@ function configure (configurationFileOrObject, options) {
} }
if (options.hasOwnProperty('cwd')) { if (options.hasOwnProperty('cwd')) {
if(config.hasOwnProperty('appenders')) { if (config.hasOwnProperty('appenders')) {
config.appenders.forEach(function(appender) { config.appenders.forEach(function(appender) {
if (!appender.hasOwnProperty('type')) return; if (!appender.hasOwnProperty('type')) return;
@ -409,8 +400,8 @@ module.exports = {
loadAppender(appender); loadAppender(appender);
}); });
//set ourselves up if we can find a default log4js.json //set ourselves up
configure(findConfiguration()); configure();
//keep the old-style layouts //keep the old-style layouts
['basicLayout','messagePassThroughLayout','colouredLayout','coloredLayout'].forEach(function(item) { ['basicLayout','messagePassThroughLayout','colouredLayout','coloredLayout'].forEach(function(item) {

View File

@ -295,72 +295,46 @@ vows.describe('log4js').addBatch({
'default setup': { 'default setup': {
topic: function() { topic: function() {
var pathLoaded, var appenderEvents = [],
logger, fakeConsole = {
modulePath = require('path').normalize(__dirname + '/../lib/log4js.json'), 'name': 'console'
mtime = Date.now(), , 'appender': function () {
fakeFS = { return function(evt) {
readdirSync: function(dir) { appenderEvents.push(evt);
return require('fs').readdirSync(dir); }
},
readFileSync: function (file, encoding) {
pathLoaded = file;
assert.equal(encoding, 'utf8');
return '{ "appenders" : [ { "type": "console", "layout": { "type": "messagePassThrough" }} ] }';
},
statSync: function (path) {
if (path === modulePath) {
return { mtime: mtime };
} else {
throw new Error("no such file");
} }
} , 'configure': function (config) {
}, return fakeConsole.appender();
appenderEvents = [],
fakeConsole = {
'name': 'console'
, 'appender': function () {
return function(evt) { appenderEvents.push(evt); }
}
, 'configure': function (config) {
return fakeConsole.appender();
}
},
globalConsole = {
log: function() { throw new Error("I should not be called."); }
},
log4js = sandbox.require(
'../lib/log4js',
{
requires: {
'fs': fakeFS
, './appenders/console': fakeConsole
},
globals: {
console: globalConsole
} }
} },
); globalConsole = {
log: function() { }
},
log4js = sandbox.require(
'../lib/log4js',
{
requires: {
'./appenders/console': fakeConsole
},
globals: {
console: globalConsole
}
}
),
logger = log4js.getLogger('a-test');
logger = log4js.getLogger('a-test');
logger.debug("this is a test"); logger.debug("this is a test");
globalConsole.log("this should be logged"); globalConsole.log("this should not be logged");
return [ pathLoaded, appenderEvents, modulePath ];
return appenderEvents;
}, },
'should use require.resolve to find log4js.json': function(args) { 'should configure a console appender': function(appenderEvents) {
var pathLoaded = args[0], modulePath = args[2];
assert.equal(pathLoaded, modulePath);
},
'should configure log4js from first log4js.json found': function(args) {
var appenderEvents = args[1];
assert.equal(appenderEvents[0].data[0], 'this is a test'); assert.equal(appenderEvents[0].data[0], 'this is a test');
}, },
'should replace console.log with log4js version': function(args) { 'should not replace console.log with log4js version': function(appenderEvents) {
var appenderEvents = args[1]; assert.equal(appenderEvents.length, 1);
assert.equal(appenderEvents[1].data[0], 'this should be logged');
} }
}, },
@ -449,7 +423,7 @@ vows.describe('log4js').addBatch({
var pathsChecked = [], var pathsChecked = [],
logEvents = [], logEvents = [],
logger, logger,
modulePath = require('path').normalize(__dirname + '/../lib/log4js.json'), modulePath = 'path/to/log4js.json',
fakeFS = { fakeFS = {
lastMtime: Date.now(), lastMtime: Date.now(),
config: { appenders: [ { type: 'console', layout: { type: 'messagePassThrough' } } ], config: { appenders: [ { type: 'console', layout: { type: 'messagePassThrough' } } ],
@ -499,7 +473,7 @@ vows.describe('log4js').addBatch({
} }
); );
log4js.configure(undefined, { reloadSecs: 30 }); log4js.configure('path/to/log4js.json', { reloadSecs: 30 });
logger = log4js.getLogger('a-test'); logger = log4js.getLogger('a-test');
logger.info("info1"); logger.info("info1");
logger.debug("debug2 - should be ignored"); logger.debug("debug2 - should be ignored");
@ -511,10 +485,10 @@ vows.describe('log4js').addBatch({
return logEvents; return logEvents;
}, },
'should configure log4js from first log4js.json found': function(logEvents) { 'should configure log4js from first log4js.json found': function(logEvents) {
assert.equal(logEvents.length, 3);
assert.equal(logEvents[0].data[0], 'info1'); assert.equal(logEvents[0].data[0], 'info1');
assert.equal(logEvents[1].data[0], 'info3'); assert.equal(logEvents[1].data[0], 'info3');
assert.equal(logEvents[2].data[0], 'debug4'); assert.equal(logEvents[2].data[0], 'debug4');
assert.equal(logEvents.length, 3);
} }
}, },