log4js-node/lib/appenders/smtp.js

76 lines
1.9 KiB
JavaScript
Raw Normal View History

2011-11-08 15:56:21 +08:00
var layouts = require("../layouts"),
mailer = require("nodemailer"),
os = require('os');
2011-11-08 15:56:21 +08:00
/**
* SMTP Appender. Sends logging events using SMTP protocol.
2011-11-08 15:56:21 +08:00
* It can either send an email on each event or group several logging events gathered during specified interval.
*
* @param config appender configuration data
2011-11-08 15:56:21 +08:00
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
* all events are buffered and sent in one email during this time; if 0 than every event sends an email
*/
function smtpAppender(config, layout) {
2011-11-08 15:56:21 +08:00
layout = layout || layouts.basicLayout;
var subjectLayout = layouts.messagePassThroughLayout;
var sendInterval = config.sendInterval*1000 || 0;
2011-11-08 15:56:21 +08:00
var logEventBuffer = [];
var sendTimer;
var transport = mailer.createTransport(config.transport, config[config.transport]);
2011-11-08 15:56:21 +08:00
function sendBuffer() {
if (logEventBuffer.length == 0)
return;
2011-11-08 15:56:21 +08:00
var firstEvent = logEventBuffer[0];
var body = "";
while (logEventBuffer.length > 0) {
body += layout(logEventBuffer.shift()) + "\n";
}
2011-11-08 15:56:21 +08:00
var msg = {
to: config.recipients,
subject: config.subject || subjectLayout(firstEvent),
text: body,
headers: {"Hostname": os.hostname()}
2011-11-08 15:56:21 +08:00
};
if (config.sender)
msg.from = config.sender;
transport.sendMail(msg, function(error, success) {
2011-11-08 15:56:21 +08:00
if (error) {
console.error("log4js.smtpAppender - Error happened ", error);
}
});
}
2011-11-08 15:56:21 +08:00
function scheduleSend() {
if (!sendTimer)
sendTimer = setTimeout(function() {
sendTimer = null;
2011-11-08 15:56:21 +08:00
sendBuffer();
}, sendInterval);
}
2011-11-08 15:56:21 +08:00
return function(loggingEvent) {
logEventBuffer.push(loggingEvent);
if (sendInterval > 0)
scheduleSend();
else
sendBuffer();
};
}
function configure(config) {
var layout;
if (config.layout) {
layout = layouts.layout(config.layout.type, config.layout);
}
return smtpAppender(config, layout);
2011-11-08 15:56:21 +08:00
}
exports.name = "smtp";
2011-11-08 15:56:21 +08:00
exports.appender = smtpAppender;
exports.configure = configure;