相信所有奮斗在一線的小伙伴,會很關心自己的系統的運行情況,一般來說,基礎設施齊全一點的公司都會有完善的報警方案,那么如果我們是一個小公司呢,不能因為基礎設施沒有,就失去對象的感知能力吧;如果我們的系統大量異常卻不能實時的觸達給我們,那么也就只會有一個結果--殺個程序猿祭天
本文簡單的介紹一種實現思路,基於error日志來實現郵件的報警方案
I. 項目環境
1. 項目依賴
本項目借助SpringBoot 2.2.1.RELEASE
+ maven 3.5.3
+ IDEA
進行開發
開一個web服務用於測試
<dependencies>
<!-- 郵件發送的核心依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
2. 配置
郵件相關配置如下,注意使用自己的用戶名 + 授權碼填充下面缺失的配置
spring:
#郵箱配置
mail:
host: smtp.163.com
from: xhhuiblog@163.com
# 使用自己的發送方用戶名 + 授權碼填充
username:
password:
default-encoding: UTF-8
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
II. 異常日志的郵件預警
1. 設計思路
接下來這個方案的主要出發點在於,當程序出現大量的異常,表明應用多半出現了問題,需要立馬發送給項目owner
要實現這個方案,關鍵點就在於異常出現的感知與上報
- 異常的捕獲,並輸出日志(這個感覺屬於標配了吧,別告訴我現在還有應用不輸出日志文件的...)
- 對於這個感知,借助logback的擴展機制,可以實現,后面介紹
- 異常上報:郵件發送
關於email的使用姿勢,推薦參考博文 SpringBoot 系列之郵件發送姿勢介紹
2. 自定義appender
定義一個用於錯誤發送的Appender,如下
public class MailUtil extends AppenderBase<ILoggingEvent> {
public static void sendMail(String title, String context) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//郵件發送人
simpleMailMessage.setFrom(ContextUtil.getEnvironment().getProperty("spring.mail.from", "bangzewu@126.com"));
//郵件接收人,可以是多個
simpleMailMessage.setTo("bangzewu@126.com");
//郵件主題
simpleMailMessage.setSubject(title);
//郵件內容
simpleMailMessage.setText(context);
JavaMailSender javaMailSender = ContextUtil.getApplicationContext().getBean(JavaMailSender.class);
javaMailSender.send(simpleMailMessage);
}
private static final long INTERVAL = 10 * 1000 * 60;
private long lastAlarmTime = 0;
@Override
protected void append(ILoggingEvent iLoggingEvent) {
if (canAlarm()) {
sendMail(iLoggingEvent.getLoggerName(), iLoggingEvent.getFormattedMessage());
}
}
private boolean canAlarm() {
// 做一個簡單的頻率過濾
long now = System.currentTimeMillis();
if (now - lastAlarmTime >= INTERVAL) {
lastAlarmTime = now;
return true;
} else {
return false;
}
}
}
3. Spring容器
上面的郵件發送中,需要使用JavaMailSender
,寫一個簡單的SpringContext工具類,用於獲取Bean/Propertiy
@Component
public class ContextUtil implements ApplicationContextAware, EnvironmentAware {
private static ApplicationContext applicationContext;
private static Environment environment;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ContextUtil.applicationContext = applicationContext;
}
@Override
public void setEnvironment(Environment environment) {
ContextUtil.environment = environment;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Environment getEnvironment() {
return environment;
}
}
4. logback配置
接下來就是在日志配置中,使用我們上面定義的Appender
logback-spring.xml
文件內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d [%t] %-5level %logger{36}.%M\(%file:%line\) - %msg%n</pattern>
<!-- 控制台也要使用UTF-8,不要使用GBK,否則會中文亂碼 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="errorAlarm" class="com.git.hui.demo.mail.util.MailUtil">
<!--如果只是想要 Error 級別的日志,那么需要過濾一下,默認是 info 級別的,ThresholdFilter-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<!-- 指定項目中某個包,當有日志操作行為時的日志記錄級別 -->
<!-- 級別依次為【從高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE -->
<!-- additivity=false 表示匹配之后,不再繼續傳遞給其他的logger-->
<logger name="com.git.hui" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT"/>
<appender-ref ref="errorAlarm"/>
</logger>
<!-- 控制台輸出日志級別 -->
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
5. 測試demo
接下來演示一下,是否可以達到我們的預期
@Slf4j
@RestController
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@GetMapping("div")
public String div(int a, int b) {
try {
return String.valueOf(a / b);
} catch (Exception e) {
log.error("div error! {}/{}", a, b, e);
return "some error!";
}
}
}
5.小結
本篇博文主要提供了一個思路,借助logback的擴展機制,來實現錯誤日志與預警郵件綁定,實現一個簡單的應用異常監控
上面這個實現只算是一個雛形,算是拋磚引玉,有更多可以豐富的細節,比如
- 飛書/釘釘通知(借助飛書釘釘的機器來報警,相比較於郵件感知性更高)
- 根據異常類型,做預警的區分
- 更高級的頻率限制等
在這里推薦一個我之前開源的預警系統,可以實現靈活預警方案配置,頻率限制,重要性升級等
- 一個可擴展的報警系統 https://github.com/liuyueyi/quick-alarm
III. 不能錯過的源碼和相關知識點
0. 項目
- 工程:https://github.com/liuyueyi/spring-boot-demo
- 源碼:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-case/430-mail-alarm
推薦關聯博文
1. 一灰灰Blog
盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激
下面一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛
- 一灰灰Blog個人博客 https://blog.hhui.top
- 一灰灰Blog-Spring專題博客 http://spring.hhui.top