首页 > 代码库 > Log4j发送邮件
Log4j发送邮件
源码地址: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?"); } } }
Log4j发送邮件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。