使用sendgrid和node.js将日志文件附加到电子邮件中。

问题描述 投票:0回答:1

我试图在一个简单的node.js应用程序中发送电子邮件,并附上刚刚用log4js创建的日志文件。我可以用sendgrid发送邮件,并且有一个附件,但附件是空的。任何帮助将是感激的。下面是app.js代码。

const fs = require('fs');
require('dotenv').config();
const sub = require('./app-sub');
const log = require('./logger').logger.getLogger('app');

// Make some log entries out to console and to app.log
log.info('******************************')
log.info('Start test1')
log.info('')
log.trace("trace message")
log.debug("Some debug messages");
log.info("some info")
log.warn("a warning")
log.error("an error")
log.fatal("a fatal error")

// Call a function in another file to test
sub.sub_funct1();

log.info('')
log.info('******************************')
log.info('End test1')

// Send email with log as attachment
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

// Read log file base 64
path = 'app.log';
attachment = fs.readFileSync(path, { encoding: 'base64' });

const msg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Test email 1',
  text: 'Results sent from log_test',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
  attachments: [
    {
      content: attachment,
      filename: 'app.log',
      type: 'text/html', // plain/text application/pdf
      disposition: 'attachment',
      content_id: 'app.log'
      // inline, attachment
    },
  ],

};
sgMail.send(msg)
  .then(result => { })
  .catch(err => console.log(err.response.body));

以及log4js的logger.js中的logger配置

const log4js = require('log4js');
const level = process.env.NODE_LOGGING_LEVEL || 'debug';

log4js.configure({
  appenders: {
    app: { type: 'file', filename: 'app.log', flags: 'w' },
    out: { type: 'stdout' },
  },
  categories: { default: { appenders: ['out', 'app'], level: level } }
});

module.exports.logger = log4js;

当我运行它的时候,我在终端和app.js同一个文件夹里的app.log文件中看到了日志输出。

[2019-12-25T15:43:46.677] [INFO] app - ******************************
[2019-12-25T15:43:46.679] [INFO] app - Start test1
[2019-12-25T15:43:46.680] [INFO] app -  
[2019-12-25T15:43:46.688] [DEBUG] app - Some debug messages 
[2019-12-25T15:43:46.689] [INFO] app - some info 
[2019-12-25T15:43:46.690] [WARN] app - a warning 
[2019-12-25T15:43:46.691] [ERROR] app - an error
[2019-12-25T15:43:46.691] [FATAL] app - a fatal error
[2019-12-25T15:43:46.692] [INFO] app - some info from app-sub
[2019-12-25T15:43:46.692] [INFO] app -  
[2019-12-25T15:43:46.692] [INFO] app - ****************************** 
[2019-12-25T15:43:46.693] [INFO] app - End test1

邮件被发送到我的gmail账户,附件名为app.log。但当我打开它时,它是空白的。所以,不知道是我在发送邮件时,文本文件的base64转换失败了,还是附件部分失败了。先谢谢你了。

node.js attachment sendgrid log4js-node
1个回答
0
投票

当年我就能把这个问题解决了,想记录一个解决方案。我认为关键是先关闭日志文件,因为它还在使用时不能附加。下面是关闭日志文件并调用我的sendEmail实用函数的代码。

log.shutown;
email.sendEmail(to, subject, body, logPath)

这里是sendMail函数

require('dotenv').config();
const sgMail = require('@sendgrid/mail');
const fs = require('fs');

function sendEmail(to, subject, body, attachmentPath) {

  // Send email with log as attachment
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);

  const msg = {
    to: to,
    from: '[email protected]',
    subject: subject,
    text: 'Results:',
    html: body
  };

  // Read log file base 64
  if (attachmentPath != undefined) {
    attachment = fs.readFileSync(attachmentPath, { encoding: 'base64' });
    msg.attachments = [
      {
        content: attachment,
        filename: attachmentPath,
        type: 'text/plain',
        disposition: 'attachment'
      },
    ]
  } else {
    msg.attachments = undefined;
  }

  sgMail.send(msg)
    .then(result => { })
    .catch(err => console.log(err.response.body));
}
© www.soinside.com 2019 - 2024. All rights reserved.