From ce8b6b06b97fd3892ba75445c5a6563265b5bce0 Mon Sep 17 00:00:00 2001 From: Gareth Jones Date: Mon, 5 Aug 2013 07:21:12 +1000 Subject: [PATCH] trying out a shutdown function --- lib/appenders/file.js | 19 ++++++++++++++++++- lib/log4js.js | 20 ++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/appenders/file.js b/lib/appenders/file.js index da0e80b..b5b3fc8 100644 --- a/lib/appenders/file.js +++ b/lib/appenders/file.js @@ -1,5 +1,6 @@ "use strict"; var layouts = require('../layouts') +, async = require('async') , path = require('path') , fs = require('fs') , streams = require('../streams') @@ -61,7 +62,12 @@ function fileAppender (file, layout, logSize, numBackups) { openFiles.push(logFile); return function(loggingEvent) { - logFile.write(layout(loggingEvent) + eol, "utf8"); + logFile.write(layout(loggingEvent) + eol, "utf8", + function() { + // just here to keep the event loop + // open - doesn't work. + return; + }); }; } @@ -78,5 +84,16 @@ function configure(config, options) { return fileAppender(config.filename, layout, config.maxLogSize, config.backups); } +function shutdown(cb) { + async.forEach(openFiles, function(file, done) { + if (!file.write(eol, "utf-8")) { + file.once('drain', function() { + file.end(done); + }); + } + }, cb); +} + exports.appender = fileAppender; exports.configure = configure; +exports.shutdown = shutdown; diff --git a/lib/log4js.js b/lib/log4js.js index fc3baca..c61272e 100644 --- a/lib/log4js.js +++ b/lib/log4js.js @@ -44,6 +44,7 @@ * Website: http://log4js.berlios.de */ var events = require('events') +, async = require('async') , fs = require('fs') , path = require('path') , util = require('util') @@ -301,6 +302,24 @@ function loadAppender(appender) { appenderMakers[appender] = appenderModule.configure.bind(appenderModule); } +function shutdown(cb) { + var allAppenders = Object.keys(appenders).reduce( + function(accum, category) { + return accum.concat(appenders[category]); + }, []); + async.forEach( + allAppenders, + function(appender, done) { + if (appender.shutdown) { + appender.shutdown(done); + } else { + done(); + } + }, + cb + ); +} + module.exports = { getLogger: getLogger, getDefaultLogger: getDefaultLogger, @@ -309,6 +328,7 @@ module.exports = { loadAppender: loadAppender, clearAppenders: clearAppenders, configure: configure, + shutdown: shutdown, replaceConsole: replaceConsole, restoreConsole: restoreConsole,