源码地址:https://github.com/mistbor/Log4jSendMail

引入activation.jar           log4j.jar            mail.jar              slf4j-api.jar              slf4j-log4j.jar

项目结构搭建如下:

log4j.properties文件内容如下:

log4j.rootLogger=info,console,MAIL
log4j.logger.org.apache.mina.filter.logging.LoggingFilter=WARN
log4j.logger.com.playsnail.core.web.filter.IdentityFilter=WARN
log4j.logger.com.d1xn.common.log.Log=WARN
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%p-%d{yyyy/MM/dd/HH\:mm\:ss}]%c{1}.(%L) - %m%n
log4j.appender.console.Threshold=INFO

######################send error through email.######################
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
#日志的错误级别
log4j.appender.MAIL.Threshold=ERROR
#缓存文件大小,日志达到2时发送Email
#log4j.appender.MAIL.BufferSize=2
#发送邮件的服务器
log4j.appender.MAIL.SMTPHost=smtp.163.com
#邮件主题
log4j.appender.MAIL.Subject=Log4JErrorMessage
#发送邮件箱的用户
log4j.appender.MAIL.SMTPUsername=projectutil@163.com
#发送邮件箱的密码
log4j.appender.MAIL.SMTPPassword=my123456
#发送邮件箱
log4j.appender.MAIL.From=projectutil@163.com
#接受邮件箱
log4j.appender.MAIL.To=projectutil@163.com
#发送邮件的格式
log4j.appender.MAIL.layout=org.apache.log4j.HTMLLayout

测试类TestLog4jSendMail(临时写入log4j配置):

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("projectutil@163.com");
            appender.setSMTPPassword("my123456");
            appender.setTo("projectutil@163.com");
            appender.setFrom("projectutil@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("测试");
        }catch (Exception e){
            e.printStackTrace();
        }    }

    public static void main(String[] args) {
        new TestLog4jSendMail();
    }
}

测试类TestLog4jSendMail2(加载log4j.properties文件)

import org.apache.log4j.Logger;

/**
 * Created by ${MiaoYing} on 2017/7/12.
 */
public class TestLog4jSendMail2 {
    public static void main(String[] args) {
        Logger logger=Logger.getLogger(TestLog4jSendMail2.class);
        int i=0;
        while (i<6){
            i+=1;
            logger.error("Do you received message?");
        }
    }
}

 

posted on 2017-07-12 23:52  miaoying  阅读(299)  评论(0编辑  收藏  举报