2011-07-24 19:58:02 +08:00
|
|
|
var layouts = require('../layouts')
|
2011-11-21 12:03:51 +08:00
|
|
|
, path = require('path')
|
2011-12-19 13:58:21 +08:00
|
|
|
, fs = require('fs')
|
|
|
|
, streams = require('../streams');
|
2011-07-24 19:58:02 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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)
|
|
|
|
*/
|
2011-11-21 12:03:51 +08:00
|
|
|
function fileAppender (file, layout, logSize, numBackups) {
|
|
|
|
var bytesWritten = 0;
|
|
|
|
file = path.normalize(file);
|
2011-07-24 19:58:02 +08:00
|
|
|
layout = layout || layouts.basicLayout;
|
|
|
|
numBackups = numBackups === undefined ? 5 : numBackups;
|
2011-07-26 16:40:41 +08:00
|
|
|
//there has to be at least one backup if logSize has been specified
|
|
|
|
numBackups = numBackups === 0 ? 1 : numBackups;
|
2011-07-24 19:58:02 +08:00
|
|
|
|
2011-12-19 13:58:21 +08:00
|
|
|
function openTheStream(file, fileSize, numFiles) {
|
2011-12-20 05:49:21 +08:00
|
|
|
var stream;
|
|
|
|
if (fileSize) {
|
|
|
|
stream = new streams.BufferedWriteStream(
|
|
|
|
new streams.RollingFileStream(
|
|
|
|
file,
|
|
|
|
fileSize,
|
|
|
|
numFiles
|
|
|
|
)
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
stream = new streams.BufferedWriteStream(fs.createWriteStream(file, { encoding: "utf8", mode: 0644, flags: 'a' }));
|
|
|
|
}
|
2011-07-24 19:58:02 +08:00
|
|
|
stream.on("error", function (err) {
|
2011-11-21 12:03:51 +08:00
|
|
|
console.error("log4js.fileAppender - Writing to file %s, error happened ", file, err);
|
2011-07-24 19:58:02 +08:00
|
|
|
});
|
|
|
|
return stream;
|
|
|
|
}
|
|
|
|
|
2011-12-19 13:58:21 +08:00
|
|
|
var logFile = openTheStream(file, logSize, numBackups);
|
2011-07-24 19:58:02 +08:00
|
|
|
|
|
|
|
//close the file on process exit.
|
|
|
|
process.on('exit', function() {
|
|
|
|
logFile.end();
|
|
|
|
});
|
|
|
|
|
|
|
|
return function(loggingEvent) {
|
2011-12-19 13:58:21 +08:00
|
|
|
logFile.write(layout(loggingEvent)+'\n', "utf8");
|
2011-07-24 19:58:02 +08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function configure(config) {
|
|
|
|
var layout;
|
|
|
|
if (config.layout) {
|
|
|
|
layout = layouts.layout(config.layout.type, config.layout);
|
|
|
|
}
|
2011-11-21 12:03:51 +08:00
|
|
|
return fileAppender(config.filename, layout, config.maxLogSize, config.backups);
|
2011-07-24 19:58:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
exports.name = "file";
|
|
|
|
exports.appender = fileAppender;
|
|
|
|
exports.configure = configure;
|