我试图在一个简单的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: 'dgarvin57@gmail.com',from: 'darvin57@gmail.com',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));
和logger.js中的log4js记录器配置:
const log4js = require('log4js');
const level = process.env.NODE_LOGGING_LEVEL || 'debug';
log4js.configure({
appenders: {
app: { type: 'file',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
该电子邮件连同名为app.log的附件发送到我的Gmail帐户。但是当我打开它时,它是空白的。因此,不确定在发送电子邮件时是否在文本文件或附件部分的base64转换上失败。提前致谢。