log4js-node/lib/appenders/smtp.js

83 lines
2.1 KiB
JavaScript
Raw Normal View History

"use strict";
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.
* It can either send an email on each event or group several
* logging events gathered during specified interval.
2011-11-08 15:56:21 +08:00
*
* @param config appender configuration data
* config.sendInterval time between log emails (in seconds), if 0
* then every event sends an email
2011-11-08 15:56:21 +08:00
* @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
*/
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() {
if (logEventBuffer.length > 0) {
var transport = mailer.createTransport(config.transport, config[config.transport]);
var firstEvent = logEventBuffer[0];
var body = "";
while (logEventBuffer.length > 0) {
body += layout(logEventBuffer.shift()) + "\n";
}
var msg = {
to: config.recipients,
subject: config.subject || subjectLayout(firstEvent),
text: body,
headers: { "Hostname": os.hostname() }
};
if (config.sender) {
msg.from = config.sender;
}
transport.sendMail(msg, function(error, success) {
if (error) {
console.error("log4js.smtpAppender - Error happened", error);
}
transport.close();
});
2013-05-25 11:04:48 +08:00
}
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;