log4j 邮件 配置

Log4j在java项目中应该非常广泛的一个工具。但经常的去检查日志是非常繁琐的一个事情,
有时,我们就需要配置log4j 发送邮件!

首先需要三个jar包:

log4j-1.2.15.jar(版本低于log4j-1.2.14.jar不支持smtp认证)、mail.jar、activation.jar




先用编码方式测试邮件是否能发送。

import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.net.SMTPAppender;

public class TestLog4jSendMail {
	static Logger logger = Logger.getLogger(TestLog4jSendMail.class);
	SMTPAppender appender = new SMTPAppender();
	public TestLog4jSendMail() {
		try {
			appender.setSMTPUsername("username");
			appender.setSMTPPassword("password");
			appender.setTo("[email protected]");
			appender.setFrom("[email protected]");
			// SMTP服务器 smtp.163.com
			appender.setSMTPHost("smtp.163.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.error("Printing ERROR Statements", e);
		}
	}
	public static void main(String args[]) {
		new TestLog4jSendMail();
	}
}



log4j.properties


log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
# 日志的错误级别
log4j.appender.MAIL.Threshold=ERROR
# 缓存文件大小,日志达到512K时发送Email
#log4j.appender.MAIL.BufferSize=0
# 发送邮件的服务器
log4j.appender.MAIL.SMTPHost=pop.ttt.com
#邮件主题
log4j.appender.MAIL.Subject=ErrorMessage
#发送邮件箱的用户
log4j.appender.MAIL.SMTPUsername=username
#发送邮件箱的密码
log4j.appender.MAIL.SMTPPassword=password
#发送邮件箱
[email protected]
#接受邮件箱
[email protected]

log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout

#com.study.logMail包下面的ERROR级别以上的log都是采用邮件发送
log4j.logger.com.study.logMail = ERROR,MAIL


Log4jSendMail.java 注意:要放在在com.study.logMail下面

package com.study.logMail;
import org.apache.log4j.Logger;

public class Log4jSendMail {
	private static final Logger logger = Logger.getLogger(Log4jSendMail.class);

	public static void main(String args[]) {
		logger.error("Do you received message?");
	}
}



用公司自己的邮件系统试过已经能发送成功了!!!!

你可能感兴趣的:(apache,.net,log4j)