smtp.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. var layouts = require("../layouts")
  3. , mailer = require("nodemailer")
  4. , os = require('os');
  5. /**
  6. * SMTP Appender. Sends logging events using SMTP protocol.
  7. * It can either send an email on each event or group several
  8. * logging events gathered during specified interval.
  9. *
  10. * @param config appender configuration data
  11. * config.sendInterval time between log emails (in seconds), if 0
  12. * then every event sends an email
  13. * @param layout a function that takes a logevent and returns a string (defaults to basicLayout).
  14. */
  15. function smtpAppender(config, layout) {
  16. layout = layout || layouts.basicLayout;
  17. var subjectLayout = layouts.messagePassThroughLayout;
  18. var sendInterval = config.sendInterval*1000 || 0;
  19. var logEventBuffer = [];
  20. var sendTimer;
  21. function sendBuffer() {
  22. if (logEventBuffer.length > 0) {
  23. var transport = mailer.createTransport(config.transport, config[config.transport]);
  24. var firstEvent = logEventBuffer[0];
  25. var body = "";
  26. while (logEventBuffer.length > 0) {
  27. body += layout(logEventBuffer.shift()) + "\n";
  28. }
  29. var msg = {
  30. to: config.recipients,
  31. subject: config.subject || subjectLayout(firstEvent),
  32. text: body,
  33. headers: { "Hostname": os.hostname() }
  34. };
  35. if (config.sender) {
  36. msg.from = config.sender;
  37. }
  38. transport.sendMail(msg, function(error, success) {
  39. if (error) {
  40. console.error("log4js.smtpAppender - Error happened", error);
  41. }
  42. transport.close();
  43. });
  44. }
  45. }
  46. function scheduleSend() {
  47. if (!sendTimer) {
  48. sendTimer = setTimeout(function() {
  49. sendTimer = null;
  50. sendBuffer();
  51. }, sendInterval);
  52. }
  53. }
  54. return function(loggingEvent) {
  55. logEventBuffer.push(loggingEvent);
  56. if (sendInterval > 0) {
  57. scheduleSend();
  58. } else {
  59. sendBuffer();
  60. }
  61. };
  62. }
  63. function configure(config) {
  64. var layout;
  65. if (config.layout) {
  66. layout = layouts.layout(config.layout.type, config.layout);
  67. }
  68. return smtpAppender(config, layout);
  69. }
  70. exports.name = "smtp";
  71. exports.appender = smtpAppender;
  72. exports.configure = configure;