public class TestLog4jSendMail {
static Logger logger = Logger.getLogger(TestLog4jSendMail.class);
SMTPAppender appender = new SMTPAppender();
public TestLog4jSendMail() {
try {
appender.setSMTPUsername("yin_jw123@126.com");
appender.setSMTPPassword("yinjianwei");
appender.setTo("yin_jw456@126.com");
appender.setFrom("yin_jw123@126.com");
// SMTP服务器 smtp.163.com
appender.setSMTPHost("smtp.126.com");
appender.setLocationInfo(true);
appender.setSubject("Test Mail From Log4J");
appender.setLayout(new PatternLayout());
appender.activateOptions();
logger.addAppender(appender);
logger.error("Hello World");
} catch (Exception e) {
e.printStackTrace();
logger.info("Printing ERROR Statements", e);
}
}
public static void main(String args[]) {
new TestLog4jSendMail();
}
}
上面的代码可以发送邮件
调用log4j.properties文件不能发送邮件
###########################send error through email.###########################
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
日志的错误级别
log4j.appender.MAIL.Threshold=ERROR
缓存文件大小,日志达到512K时发送Email
log4j.appender.MAIL.BufferSize=0
发送邮件的服务器
log4j.appender.MAIL.SMTPHost=smtp.126.com
#邮件主题
log4j.appender.MAIL.Subject=ErrorMessage
#发送邮件箱的用户
log4j.appender.MAIL.SMTPUsername=yin_jw123@126.com
#发送邮件箱的密码
log4j.appender.MAIL.SMTPPassword=yinjianwei
#发送邮件箱
log4j.appender.MAIL.From=yin_jw123@126.com
#接受邮件箱
log4j.appender.MAIL.To=yin_jw456@126.com
log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout
#com.study.logMail包下面的ERROR级别以上的log都是采用邮件发送
log4j.logger.com.study.logMail = ERROR,MAIL
public class Log4jSendMail {
public static void main(String args[]) throws InterruptedException {
PropertyConfigurator.configure(Log4jSendMail.class.getResource("/log4j.properties"));
Logger logger = Logger.getLogger(Log4jSendMail.class);
while (true) {
Thread.sleep(5000);
logger.error("Do you received message?");
}
}
}
为什么??? 在线等 加急!