diff --git a/lib/appenders/file.js b/lib/appenders/file.js index fc9868c..31afa73 100644 --- a/lib/appenders/file.js +++ b/lib/appenders/file.js @@ -5,6 +5,9 @@ var layouts = require('../layouts') , os = require('os') , eol = os.EOL || '\n'; +var openFiles = []; +var listenerAtttached = false; + /** * File Appender writing the logs to a text file. Supports rolling of logs by size. * @@ -42,10 +45,18 @@ function fileAppender (file, layout, logSize, numBackups) { var logFile = openTheStream(file, logSize, numBackups); + // push file to the stack of open handlers + openFiles.push(logFile); + //close the file on process exit. - process.on('exit', function() { - logFile.end(); - }); + if (!listenerAtttached) { + listenerAtttached = true; + process.on('exit', function() { + openFiles.forEach(function (file) { + file.end(); + }); + }); + } return function(loggingEvent) { logFile.write(layout(loggingEvent) + eol, "utf8"); diff --git a/test/fileAppender-test.js b/test/fileAppender-test.js index eb26c9c..7d6fdd9 100644 --- a/test/fileAppender-test.js +++ b/test/fileAppender-test.js @@ -15,6 +15,24 @@ function remove(filename) { } vows.describe('log4js fileAppender').addBatch({ + 'adding multiple fileAppenders': { + topic: function () { + var listenersCount = process.listeners('exit').length + , logger = log4js.getLogger('default-settings') + , count = 5, logfile; + + while (count--) { + logfile = path.join(__dirname, '/fa-default-test' + count + '.log'); + log4js.addAppender(require('../lib/appenders/file').appender(logfile), 'default-settings'); + } + + return listenersCount; + }, + + 'does not adds more than one `exit` listeners': function (initialCount) { + assert.ok(process.listeners('exit').length <= initialCount + 1); + } + }, 'with default fileAppender settings': { topic: function() {