Persist logging config across invocations

This commit is contained in:
csausdev 2011-01-16 13:05:13 +11:00
parent cf7d5f681a
commit c6dd2398ab
2 changed files with 498 additions and 471 deletions

View File

@ -44,17 +44,13 @@
* @static
* Website: http://log4js.berlios.de
*/
module.exports = function (fileSystem, standardOutput, configPaths) {
var events = require('events'),
path = require('path'),
sys = require('sys'),
fs = fileSystem || require('fs'),
standardOutput = standardOutput || sys.puts,
configPaths = configPaths || require.paths,
DEFAULT_CATEGORY = '[default]',
ALL_CATEGORIES = '[all]',
loggers = {},
appenders = {},
loggers = {},
levels = {
ALL: new Level(Number.MIN_VALUE, "ALL", "grey"),
TRACE: new Level(5000, "TRACE", "blue"),
@ -66,22 +62,22 @@ module.exports = function (fileSystem, standardOutput, configPaths) {
OFF: new Level(Number.MAX_VALUE, "OFF", "grey")
},
appenderMakers = {
"file": function(config) {
"file": function(config, fileAppender) {
var layout;
if (config.layout) {
layout = layoutMakers[config.layout.type](config.layout);
}
return fileAppender(config.filename, layout, config.maxLogSize, config.backups, config.pollInterval);
},
"console": function(config) {
"console": function(config, fileAppender, consoleAppender) {
var layout;
if (config.layout) {
layout = layoutMakers[config.layout.type](config.layout);
}
return consoleAppender(layout);
},
"logLevelFilter": function(config) {
var appender = appenderMakers[config.appender.type](config.appender);
"logLevelFilter": function(config, fileAppender, consoleAppender) {
var appender = appenderMakers[config.appender.type](config.appender, fileAppender, consoleAppender);
return logLevelFilter(config.level, appender);
}
},
@ -158,10 +154,11 @@ module.exports = function (fileSystem, standardOutput, configPaths) {
loggers[category].addListener("log", appender);
}
});
appenders.count = appenders.count ? appenders.count++ : 1;
}
function clearAppenders () {
appenders = [];
appenders = {};
for (var logger in loggers) {
if (loggers.hasOwnProperty(logger)) {
loggers[logger].removeAllListeners("log");
@ -169,42 +166,11 @@ module.exports = function (fileSystem, standardOutput, configPaths) {
}
}
function configure (configurationFile) {
if (configurationFile) {
try {
var config = JSON.parse(fs.readFileSync(configurationFile, "utf8"));
configureAppenders(config.appenders);
configureLevels(config.levels);
} catch (e) {
throw new Error("Problem reading log4js config file " + configurationFile + ". Error was " + e.message);
}
}
}
function findConfiguration() {
//add current directory onto the list of configPaths
var paths = ['.'].concat(configPaths);
//add this module's directory to the end of the list, so that we pick up the default config
paths.push(__dirname);
var pathsWithConfig = paths.filter( function (pathToCheck) {
try {
fs.statSync(path.join(pathToCheck, "log4js.json"));
return true;
} catch (e) {
return false;
}
});
if (pathsWithConfig.length > 0) {
return path.join(pathsWithConfig[0], 'log4js.json');
}
return undefined;
}
function configureAppenders(appenderList) {
function configureAppenders(appenderList, fileAppender, consoleAppender) {
clearAppenders();
if (appenderList) {
appenderList.forEach(function(appenderConfig) {
var appender = appenderMakers[appenderConfig.type](appenderConfig);
var appender = appenderMakers[appenderConfig.type](appenderConfig, fileAppender, consoleAppender);
if (appender) {
addAppender(appender, appenderConfig.category);
} else {
@ -338,78 +304,6 @@ module.exports = function (fileSystem, standardOutput, configPaths) {
return getLogger(DEFAULT_CATEGORY);
}
function consoleAppender (layout) {
layout = layout || colouredLayout;
return function(loggingEvent) {
standardOutput(layout(loggingEvent));
};
}
/**
* File Appender writing the logs to a text file. Supports rolling of logs by size.
*
* @param file file log messages will be written to
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
* @param logSize - the maximum size (in bytes) for a log file, if not provided then logs won't be rotated.
* @param numBackups - the number of log files to keep after logSize has been reached (default 5)
* @param filePollInterval - the time in seconds between file size checks (default 30s)
*/
function fileAppender (file, layout, logSize, numBackups, filePollInterval) {
layout = layout || basicLayout;
//syncs are generally bad, but we need
//the file to be open before we start doing any writing.
var logFile = fs.openSync(file, 'a', 0644);
if (logSize > 0) {
setupLogRolling(logFile, file, logSize, numBackups || 5, (filePollInterval * 1000) || 30000);
}
return function(loggingEvent) {
fs.write(logFile, layout(loggingEvent)+'\n', null, "utf8");
};
}
function setupLogRolling (logFile, filename, logSize, numBackups, filePollInterval) {
fs.watchFile(filename,
{
persistent: false,
interval: filePollInterval
},
function (curr, prev) {
if (curr.size >= logSize) {
rollThatLog(logFile, filename, numBackups);
}
}
);
}
function rollThatLog (logFile, filename, numBackups) {
//doing all of this fs stuff sync, because I don't want to lose any log events.
//first close the current one.
fs.closeSync(logFile);
//roll the backups (rename file.n-1 to file.n, where n <= numBackups)
for (var i=numBackups; i > 0; i--) {
if (i > 1) {
if (fileExists(filename + '.' + (i-1))) {
fs.renameSync(filename+'.'+(i-1), filename+'.'+i);
}
} else {
fs.renameSync(filename, filename+'.1');
}
}
//open it up again
logFile = fs.openSync(filename, 'a', 0644);
}
function fileExists (filename) {
try {
fs.statSync(filename);
return true;
} catch (e) {
return false;
}
}
function logLevelFilter (levelString, appender) {
var level = Level.toLevel(levelString);
return function(logEvent) {
@ -618,6 +512,116 @@ module.exports = function (fileSystem, standardOutput, configPaths) {
};
module.exports = function (fileSystem, standardOutput, configPaths) {
var fs = fileSystem || require('fs'),
standardOutput = standardOutput || sys.puts,
configPaths = configPaths || require.paths;
function consoleAppender (layout) {
layout = layout || colouredLayout;
return function(loggingEvent) {
standardOutput(layout(loggingEvent));
};
}
/**
* File Appender writing the logs to a text file. Supports rolling of logs by size.
*
* @param file file log messages will be written to
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
* @param logSize - the maximum size (in bytes) for a log file, if not provided then logs won't be rotated.
* @param numBackups - the number of log files to keep after logSize has been reached (default 5)
* @param filePollInterval - the time in seconds between file size checks (default 30s)
*/
function fileAppender (file, layout, logSize, numBackups, filePollInterval) {
layout = layout || basicLayout;
//syncs are generally bad, but we need
//the file to be open before we start doing any writing.
var logFile = fs.openSync(file, 'a', 0644);
if (logSize > 0) {
setupLogRolling(logFile, file, logSize, numBackups || 5, (filePollInterval * 1000) || 30000);
}
return function(loggingEvent) {
fs.write(logFile, layout(loggingEvent)+'\n', null, "utf8");
};
}
function setupLogRolling (logFile, filename, logSize, numBackups, filePollInterval) {
fs.watchFile(filename,
{
persistent: false,
interval: filePollInterval
},
function (curr, prev) {
if (curr.size >= logSize) {
rollThatLog(logFile, filename, numBackups);
}
}
);
}
function rollThatLog (logFile, filename, numBackups) {
//doing all of this fs stuff sync, because I don't want to lose any log events.
//first close the current one.
fs.closeSync(logFile);
//roll the backups (rename file.n-1 to file.n, where n <= numBackups)
for (var i=numBackups; i > 0; i--) {
if (i > 1) {
if (fileExists(filename + '.' + (i-1))) {
fs.renameSync(filename+'.'+(i-1), filename+'.'+i);
}
} else {
fs.renameSync(filename, filename+'.1');
}
}
//open it up again
logFile = fs.openSync(filename, 'a', 0644);
}
function fileExists (filename) {
try {
fs.statSync(filename);
return true;
} catch (e) {
return false;
}
}
function configure (configurationFile) {
if (configurationFile) {
try {
var config = JSON.parse(fs.readFileSync(configurationFile, "utf8"));
configureAppenders(config.appenders, fileAppender, consoleAppender);
configureLevels(config.levels);
} catch (e) {
throw new Error("Problem reading log4js config file " + configurationFile + ". Error was \"" + e.message + "\" ("+e.stack+")");
}
}
}
function findConfiguration() {
//add current directory onto the list of configPaths
var paths = ['.'].concat(configPaths);
//add this module's directory to the end of the list, so that we pick up the default config
paths.push(__dirname);
var pathsWithConfig = paths.filter( function (pathToCheck) {
try {
fs.statSync(path.join(pathToCheck, "log4js.json"));
return true;
} catch (e) {
return false;
}
});
if (pathsWithConfig.length > 0) {
return path.join(pathsWithConfig[0], 'log4js.json');
}
return undefined;
}
function replaceConsole(logger) {
function replaceWith (fn) {
return function() {
@ -634,10 +638,13 @@ module.exports = function (fileSystem, standardOutput, configPaths) {
}
//do we already have appenders?
if (!appenders.count) {
//set ourselves up if we can find a default log4js.json
configure(findConfiguration());
//replace console.log, etc with log4js versions
replaceConsole(getLogger("console"));
}
return {
getLogger: getLogger,

View File

@ -247,7 +247,9 @@ vows.describe('log4js').addBatch({
'with no appenders defined' : {
topic: function() {
var logger, message, log4js = require('../lib/log4js')(null, function (msg) { message = msg; } );
var logger, message, log4jsFn = require('../lib/log4js'), log4js;
log4jsFn().clearAppenders();
log4js = log4jsFn(null, function (msg) { message = msg; } );
logger = log4js.getLogger("some-logger");
logger.debug("This is a test");
return message;
@ -364,10 +366,15 @@ vows.describe('log4js').addBatch({
},
fakeConsoleLog = function (msg) { message = msg; },
fakeRequirePath = [ '/a/b/c', '/some/other/path', '/path/to/config', '/some/later/directory' ],
log4js = require('../lib/log4js')(fakeFS, fakeConsoleLog, fakeRequirePath),
log4jsFn = require('../lib/log4js'),
log4js, logger;
log4jsFn().clearAppenders();
log4js = log4jsFn(fakeFS, fakeConsoleLog, fakeRequirePath);
logger = log4js.getLogger('a-test');
logger.debug("this is a test");
return [ pathsChecked, message ];
},
@ -478,8 +485,8 @@ vows.describe('log4js').addBatch({
topic: function() {
var log4js = require('../lib/log4js')(), logEvents = [], logger;
log4js.clearAppenders();
log4js.addAppender(log4js.logLevelFilter('ERROR', function(evt) { logEvents.push(evt); }));
logger = log4js.getLogger();
log4js.addAppender(log4js.logLevelFilter('ERROR', function(evt) { logEvents.push(evt); }), "logLevelTest");
logger = log4js.getLogger("logLevelTest");
logger.debug('this should not trigger an event');
logger.warn('neither should this');
logger.error('this should, though');
@ -535,6 +542,19 @@ vows.describe('log4js').addBatch({
assert.equal(logEvent.message, "tracing");
assert.equal(logEvent.level.toString(), "TRACE");
}
},
'configuration persistence' : {
'should maintain appenders between requires': function () {
var logEvent, firstLog4js = require('../lib/log4js')(), secondLog4js;
firstLog4js.clearAppenders();
firstLog4js.addAppender(function(evt) { logEvent = evt; });
secondLog4js = require('../lib/log4js')();
secondLog4js.getLogger().info("This should go to the appender defined in firstLog4js");
assert.equal(logEvent.message, "This should go to the appender defined in firstLog4js");
}
}
}).export(module);