log4js-node/lib/appenders/smtp.js

81 lines
2.0 KiB
JavaScript
Raw Normal View History

2011-11-08 15:56:21 +08:00
var layouts = require("../layouts"),
2013-05-25 11:04:48 +08:00
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;
2011-11-08 15:56:21 +08:00
function sendBuffer() {
2013-05-25 11:04:48 +08:00
if (logEventBuffer.length == 0) {
2011-11-08 15:56:21 +08:00
return;
2013-05-25 11:04:48 +08:00
}
2013-05-25 11:04:48 +08:00
var transport = mailer.createTransport(config.transport, config[config.transport]);
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
};
2013-05-25 11:04:48 +08:00
if (config.sender) {
msg.from = config.sender;
2013-05-25 11:04:48 +08:00
}
transport.sendMail(msg, function(error, success) {
2011-11-08 15:56:21 +08:00
if (error) {
console.error("log4js.smtpAppender - Error happened ", error);
}
2013-05-25 11:04:48 +08:00
transport.close();
2011-11-08 15:56:21 +08:00
});
}
2011-11-08 15:56:21 +08:00
function scheduleSend() {
2013-05-25 11:04:48 +08:00
if (!sendTimer) {
2011-11-08 15:56:21 +08:00
sendTimer = setTimeout(function() {
sendTimer = null;
2011-11-08 15:56:21 +08:00
sendBuffer();
}, sendInterval);
2013-05-25 11:04:48 +08:00
}
2011-11-08 15:56:21 +08:00
}
2011-11-08 15:56:21 +08:00
return function(loggingEvent) {
logEventBuffer.push(loggingEvent);
2013-05-25 11:04:48 +08:00
if (sendInterval > 0) {
2011-11-08 15:56:21 +08:00
scheduleSend();
2013-05-25 11:04:48 +08:00
} else {
2011-11-08 15:56:21 +08:00
sendBuffer();
2013-05-25 11:04:48 +08:00
}
2011-11-08 15:56:21 +08:00
};
}
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;