开发过程中,难免会有发生错误或异常的时候,有些是需要及时通知到相关开发人员的。logback可以通过简单的配置达到邮件告警的目的。
一、错误告警
如下配置,所有Error级别的log发送邮件告警给receiver(多个receiver以逗号分隔)
%d{yyyy-MM-dd HH:mm:ss.SSS} [%level][%thread]:%logger{50} [%method:%line] %msg%n 1 ${smtpHost} ${smtpPort} ${username} ${password} ${from} ${receiver} 【test-email Error】【${env}环境】: %logger{20} - %m %d{yyyy-MM-dd HH:mm:ss.SSS}%level%thread%logger{35}%message ERROR ACCEPT DENY
Error级别日志:
log.error("an unexpected error!");
收到告警邮件:
记入ex,可以看到详细的堆栈信息。
a、springProperty 从spring读取配置
scope:context 参考()
name:定义的变量名
source:需要spring配置的节点名称。(eg:log.email.receiver=xxx@126.com,yyy@qq.com)
defaultValue:默认值
二、自定义告警
上面是对所有Error级别日志的告警,有时候需要对正常业务的邮件通知,此时可以用Mark来发邮件。
%d{yyyy-MM-dd HH:mm:ss.SSS} [%level][%thread]:%logger{50} [%method:%line] %msg%n 1 ${smtpHost} ${smtpPort} ${username} ${password} ${from} ${receiver} 【开发人员关注】【${env}环境】 %d{yyyy-MM-dd HH:mm:ss.SSS}%level%thread%logger{35}%message DEVELOP
Mark邮件示例:
log.info(MarkerFactory.getMarker("DEVELOP"), "notify developers!");
邮件:
三、自定义邮件格式
邮件自定义格式。实现自定义的 HTMLLayout:
public class MyHtmlLayout extends HTMLLayout { IThrowableRendererthrowableRenderer; private String tag; public MyHtmlLayout() { super(); this.throwableRenderer = new DefaultThrowableRenderer(); } @Override public String doLayout(ILoggingEvent event) { StringBuilder buf = new StringBuilder(); this.startNewTableIfLimitReached(buf); boolean odd = true; if((this.counter++ & 1L) == 0L) { odd = false; } String level = event.getLevel().toString().toLowerCase(); buf.append(CoreConstants.LINE_SEPARATOR); buf.append(""); } else { buf.append(" even\">"); } buf.append(CoreConstants.LINE_SEPARATOR); for(Converter c = this.head; c != null; c = c.getNext()) { this.appendEventToBuffer(buf, c, event); } buf.append(""); buf.append(CoreConstants.LINE_SEPARATOR); if(event.getThrowableProxy() != null) { throwableRenderer.render(buf, event); } return buf.toString(); } private void appendEventToBuffer(StringBuilder buf, Converter c, ILoggingEvent event) { buf.append(""); buf.append(Transform.escapeTags(c.convert(event)) + ",my tag:" + tag); buf.append(""); buf.append(CoreConstants.LINE_SEPARATOR); } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; }}
将logback-spring.xml配置改为(配置的tag):
%d{yyyy-MM-dd HH:mm:ss.SSS}%level%thread%logger{35}%message this is my layout tag
四、记日志报错
参考: