2 var layouts = require('../layouts')
3 , path = require('path')
5 , streams = require('../streams')
9 , levels = require('../levels');
11 //close open files on process exit.
12 process.on('exit', function() {
13 openFiles.forEach(function (file) {
19 * File Appender writing the logs to a text file. Supports rolling of logs by size.
21 * @param file file log messages will be written to
22 * @param layout a function that takes a logevent and returns a string
23 * (defaults to basicLayout).
24 * @param logSize - the maximum size (in bytes) for a log file,
25 * if not provided then logs won't be rotated.
26 * @param numBackups - the number of log files to keep after logSize
27 * has been reached (default 5)
28 * @param compress - flag that controls log file compression
29 * @param timezoneOffset - optional timezone offset in minutes (default system local)
31 function fileAppender (file, layout, logSize, numBackups, compress, timezoneOffset) {
33 file = path.normalize(file);
34 layout = layout || layouts.basicLayout;
35 numBackups = numBackups === undefined ? 5 : numBackups;
36 //there has to be at least one backup if logSize has been specified
37 numBackups = numBackups === 0 ? 1 : numBackups;
39 function openTheStream(file, fileSize, numFiles) {
42 stream = new streams.RollingFileStream(
46 { "compress": compress }
49 stream = fs.createWriteStream(
52 mode: parseInt('0644', 8),
56 stream.on("error", function (err) {
57 console.error("log4js.fileAppender - Writing to file %s, error happened ", file, err);
62 var logFile = openTheStream(file, logSize, numBackups);
64 // push file to the stack of open handlers
65 openFiles.push(logFile);
67 return function(loggingEvent) {
68 logFile.write(layout(loggingEvent, timezoneOffset) + eol, "utf8");
73 function configure(config, options) {
76 layout = layouts.layout(config.layout.type, config.layout);
79 if (options && options.cwd && !config.absolute) {
80 config.filename = path.join(options.cwd, config.filename);
93 function shutdown(cb) {
96 var complete = function(err) {
99 if (completed >= openFiles.length) {
103 if (!openFiles.length) {
106 openFiles.forEach(function(file) {
107 if (!file.write(eol, "utf-8")) {
108 file.once('drain', function() {
117 exports.appender = fileAppender;
118 exports.configure = configure;
119 exports.shutdown = shutdown;