SpringBoot combat email alarm based on exception log

Time:2022-9-23

SpringBoot combat email alarm based on exception log

SpringBoot combat email alarm based on exception log

I believe that all the small partners who are struggling on the front line will be very concerned about the operation of their own systems. Generally speaking, companies with complete infrastructure will have a complete alarm plan. If we are a small company, it cannot be because of lack of infrastructure. , just lose the perception ability of the object; if there are a lot of abnormalities in our system but cannot reach us in real time, then there will only be one result – kill a programmer and sacrifice to the sky

This article briefly introduces an implementation idea, based on the error log to realize the email alarm scheme

<!– more –>

I. Project Environment

1. Project dependencies

This project usesSpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEAto develop

Open a web service for testing

<dependencies>
    <! -- Core Dependencies of Email Sending -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
</dependencies>

2. Configuration

The mail-related configuration is as follows, pay attention to use your own username + authorization code to fill in the missing configuration below

spring:
  #Email configuration
  mail:
    host: smtp.163.com
    from: [email protected]
    # Fill with your own sender username + authorization code
    username:
    password:
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

II. Email alerts for abnormal logs

1. Design ideas

The main starting point of the next plan is that when a large number of exceptions occur in the program, it indicates that most of the applications have problems and need to be sent to the project owner immediately.

To realize this solution, the key point is the perception and reporting of abnormal occurrences

  • Capture exceptions and output logs (this feels standard, don’t tell me that there are still applications that don’t output log files…)

    • For this perception, it can be achieved with the help of logback’s extension mechanism, which will be described later.
  • Abnormal reporting: Email sending

Regarding the use posture of email, it is recommended to refer to the introduction to the email sending posture of the SpringBoot series of blog posts

2. Custom appenders

Define an Appender for error sending, as follows

public class MailUtil extends AppenderBase<ILoggingEvent> {

    public static void sendMail(String title, String context) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // mail sender
        simpleMailMessage.setFrom(ContextUtil.getEnvironment().getProperty("spring.mail.from", "[email protected]"));
        // Mail recipient, can be multiple
        simpleMailMessage.setTo("[email protected]");
        //Email Subject
        simpleMailMessage.setSubject(title);
        //content of email
        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() {
        // do a simple frequency filter
        long now = System.currentTimeMillis();
        if (now - lastAlarmTime >= INTERVAL) {
            lastAlarmTime = now;
            return true;
        } else {
            return false;
        }
    }
}

3. Spring container

In the above email sending, you need to useJavaMailSender, write a simple SpringContext tool class to get 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 configuration

The next step is to use the Appender we defined above in the log configuration

logback-spring.xmlThe contents of the file are as follows:

<?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>
            <! -- The console should also use UTF-8, do not use GBK, otherwise you will get Chinese garble -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <appender name="errorAlarm" class="com.git.hui.demo.mail.util.MailUtil">
        <! - If you want only logs of the Error level, then filter it. The default is info, and ThresholdFilter-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
    </appender>


    <! -- Specifies the logging level of a package in the project when logging operations are performed -->
    <! The levels are from high to low: FATAL > ERROR > WARN > INFO > DEBUG > TRACE -->
    <! -- additivity=false indicates that a match is not passed to another logger-->
    <logger name="com.git.hui" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="errorAlarm"/>
    </logger>

    <! -- Console output log level -->
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

5. Test the demo

Next, let’s demonstrate whether it can meet our expectations

@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!";
        }
    }
}

SpringBoot combat email alarm based on exception log

5. Summary

This blog post mainly provides an idea, with the help of the extension mechanism of logback, to realize the binding of error log and warning email, and realize a simple application exception monitoring

The above implementation is only a prototype, it can be regarded as an introduction, there are more details that can be enriched, such as

  • Feishu/Dingding notification (with the help of Feishu’s Dingding machine to alarm, it is more sensitive than email)
  • According to the type of abnormality, make the distinction of early warning
  • More advanced frequency limiting, etc.

Here I recommend an early warning system that I have open sourced before, which can realize flexible early warning scheme configuration, frequency limit, importance upgrade, etc.

  • An extensible alarm system https://github.com/liuyueyi/quick-alarm

III. Source code and related knowledge points that cannot be missed

0. Project

  • Engineering: https://github.com/liuyueyi/spring-boot-demo
  • Source code: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-case/430-mail-alarm

Recommended related blog posts

  • Introduction to the Email Sending Posture of the SpringBoot Series

1. A gray blog

It is not as good as a letter. The above content is purely from the family. Due to limited personal ability, there are inevitably omissions and mistakes. If you find bugs or have better suggestions, you are welcome to criticize and correct them. Thank you very much.

The following is a gray personal blog, recording all blog posts in study and work, welcome everyone to visit

  • A Hui Hui Blog Personal blog https://blog.hhui.top
  • A gray blog-Spring special blog http://spring.hhui.top

SpringBoot combat email alarm based on exception log

Recommended Today

Python study notes, crawling Biquge novels

I learned the basic grammar, and then I saw someone on the Internet sharing the use of python to crawl novels, and I copied the code and tried it myself. 1. The environment is ready to install BeautifulSoup4 and lxml & C:/Python39/python.exe -m pip install –user BeautifulSoup4& C:/Python39/python.exe -m pip install –user lxml 2. Renamed […]