1. Introduction

Monitoring Web applications in production is essential. We can monitor application health, performance and other metrics in near real time to respond to unexpected situations. Avoid some failures. For Spring Boot applications, we can use a lightweight monitoring tool Spring Boot Admin (SBA) to monitor.

2. Spring Boot Admin

Spring Boot Admin is an open-source software program designed by German software engineer Johannes Edmeier to manage and monitor Spring Boot applications. The latest official release that has been accepted into Spring Initializr as of the time of publication is 2.1.6 and the SNAPSHOT is 2.0-snapshot. C/S architecture style. Applications are registered with the Spring Boot Admin Server as a Spring Boot Admin Client (via HTTP) or discovered using a Spring Cloud registry (such as Eureka, Consul). The SERVER program uses Spring Webflux, a responsive Web framework. The display UI uses vue. js to show some monitoring on endpoints of Spring Boot Admin Client through Spring Boot. Common functions or monitoring are as follows:

  • Show health
  • Displays application metrics details, for example
    • JVM and memory metrics
    • Micrometer to measure the
    • Data source index
    • Cache indicators
  • Display the build information number
  • Watch and download log files
  • downloadheapdump
  • To viewjvmSystem and environment properties
  • View Spring Boot configuration properties
  • Support for Spring Cloud’s environment endpoints and refresh endpoints
  • Support K8s
  • Easy to use log level management
  • withJMX-beansinteraction
  • Viewing a thread dump
  • To viewhttptracking
  • To viewauditevents
  • To viewhttp-endpoints
  • Viewing scheduled Tasks
  • View and Delete active sessions (using Spring Session)
  • To viewFlyway/LiquibaseDatabase Migration
  • Notification of status changes (via email, Slack, Hipchat, etc., with support for nailing)
  • Event logs of state changes (nonpersistent)

3. Fast integration

Next, let’s integrate Spring Boot Admin into the Spring Boot project. Note version compatibility, which can be verified by Spring Initializr.

3.1 Configuring the Spring Boot Admin Server

It is recommended that the Spring Boot Admin Server run independently as a Spring Boot JAR application. Just add the following dependencies to your POM.xml:

 <dependency>
     <groupId>de.codecentric</groupId>
     <artifactId>spring-boot-admin-starter-server</artifactId>
     <version>2.2.0 - the SNAPSHOT</version>
 </dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
<! -- Production needs to ensure the security of monitoring -->
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
Copy the code

Then introduce the Spring Boot AdminServer configuration by adding @enableadminServer to the configuration:

@EnableAdminServer @SpringBootApplication public class SpringBootAdminApplication { public static void main(String[] args) { SpringApplication.run(SpringBootAdminApplication.class, args); }}Copy the code

3.2 Configuring Spring Boot Admin

Every application to register must include the Spring Boot Admin Client. To protect endpoints, you should also add security dependencies on spring-boot-starter-security.

 <dependency>
     <groupId>de.codecentric</groupId>
     <artifactId>spring-boot-admin-starter-client</artifactId>
     <version>2.2.0 - the SNAPSHOT</version>
 </dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
Copy the code

Then add the following configuration to the application.yml of the client application:

  spring:
     boot:
       admin:
         client:
     # Spring Boot Admin Server address http://localhost:8080 can be customized
             url:  http://localhost:8080 
     # By default, most endpoints are not exposed over HTTP, we expose all endpoints. For production, you should carefully choose which endpoints to expose.
  management:
    endpoints:
      web:
        exposure:
          include: The '*'
    endpoint:
        health:
          show-details: ALWAYS
Copy the code

Start the SBA server and client respectively. The following monitoring page is displayed when you open the server page http://localhost:8080:

In addition, you can obtain specific monitoring indicators of admin-client:

If you are already using Spring Cloud Discovery (Eureka, Consul, etc.) for your application, the Spring Boot Admin client is not required. Simply add DiscoveryClient to the Spring Boot Admin Server and the rest is done through automatic configuration, as you can see with the official example.

4. Spring Boot Admin secure access control

Application monitoring indicators are extremely sensitive data. Therefore, production must increase security access control to avoid leakage events. You can use the security framework you are good at to do access control. Here we use Spring Security to protect our Spring Boot Admin.

4.1 Protecting the Spring Boot Admin Server

addSpring Security StarterRely on:

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
Copy the code

Set the management account information

  spring:
    security:
      user:
        name: SBA_admin
        password: SBA_password
        roles: SBA_ADMIN
Copy the code

Configure secure path access control

 package cn.felord.admin.server.configuer;
 
 import de.codecentric.boot.admin.server.config.AdminServerProperties;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.http.HttpMethod;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
 import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
 import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
 
 import java.util.UUID;
 
 /**
  * The type Security secure config.
  *
  * @author Felordcn
  * @since19 "* / 2019/10 /
 @Configuration
 public class AdminServerSecurityConfig extends WebSecurityConfigurerAdapter {
     private final AdminServerProperties adminServer;
 
     /**
      * Instantiates a new Security secure config.
      *
      * @param adminServer the admin server
      */
     public AdminServerSecurityConfig(AdminServerProperties adminServer) {
         this.adminServer = adminServer;
     }
 
     @Override
     protected void configure(HttpSecurity http) throws Exception {
         // @formatter:off
         SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
         successHandler.setTargetUrlParameter("redirectTo");
         final String adminServerContextPath = this.adminServer.getContextPath();
         successHandler.setDefaultTargetUrl(adminServerContextPath+"/");
 
         http.authorizeRequests()
                 .antMatchers(adminServerContextPath + "/assets/**").permitAll() / / < 1 >
                 .antMatchers(adminServerContextPath + "/login").permitAll()
                 .anyRequest().authenticated() / / < 2 >
                 .and()
                 .formLogin().loginPage(adminServerContextPath + "/login").successHandler(successHandler).and() / / < 3 >
                 .logout().logoutUrl(adminServerContextPath + "/logout").and()
                 .httpBasic().and() / / < 4 >
                 .csrf()
                 .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) / / < 5 >
                 .ignoringRequestMatchers(
                         new AntPathRequestMatcher(adminServerContextPath + "/instances", HttpMethod.POST.toString()),  / / < 6 >
                         new AntPathRequestMatcher(adminServerContextPath + "/instances/*", HttpMethod.DELETE.toString()),  / / < 6 >
                         new AntPathRequestMatcher(adminServerContextPath + "/actuator/**")  / / < 7 >
                 )
                 .and()
                 .rememberMe().key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600); }}Copy the code

Then start SBA Server http://localhost:8237 and the login page will be displayed. Enter the account secret you have configured:

4.2 Protecting the Spring Boot Admin Client Endpoint

After the server endpoints are controlled, clients register with permissions, and some of the endpoints of the clients must be protected.

addSpring Security StarterRely on:

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
Copy the code

Set the security account information

  spring:
    security:
      user:
        name: SBA_admin
        password: SBA_password
        roles: SBA_ADMIN
Copy the code

Example Set the security account information of the server

Configure the security account that we configured in the Spring Boot Admin server configuration into the following properties:

 boot:
     admin:
       client:
         # Spring Boot Admin Server Admin account
         username: SBA_admin
         password: SBA_password
Copy the code

Protecting Actuator endpoints

When the executor endpoints are secured with HTTP Basic authentication, SBA Server requires credentials to access them. So we use the following configuration to authorize servers to access the endpoints:

 spring:
   boot:
     admin:
       client:
         instance:
           metadata:
 Here is the account secret we set in the step of setting the security account information of client
             user.name: ${spring.security.user.name}
             user.password: ${spring.security.user.password} 
Copy the code

Just start the client application.

Please note: if you change HTTP BASIC to access the endpoint, the above configuration will be invalid and you may need to customize itHttpHeadersProviderTo meet your needs.

5. Step up your game

Spring Boot Admin also provides some common features.

5.1 Viewing Logs

By default, log files are not accessible through the executor endpoint and therefore are not visible in Spring Boot Admin. To enable the log file executor endpoint, you need to set either logging.path or logging.file.

Spring Boot Admin will detect anything that looks like a URL and render it as a hyperlink. ANSI color escape is also supported. You need to set up a custom file logging mode because Spring Boot’s default mode does not use colors.

In the case of logging.file, we add the following configuration to the client application.yml:

 logging:
    file: /application.log 
    pattern:
      file: '% CLR (% d {MM - dd yyyy - HH: MM: ss. The SSS}) {abbreviation} % CLR (% 5 p) % CLR (${PID} {magenta} % CLR (-) {abbreviation} % CLR ([% 15.15 t]) {abbreviation} % the CLR (% 40.40 logger {39}) CLR (:) {abbreviation} {cyan} % % m % n % wEx '
Copy the code

Then the SBA console displays:

5.2 Adding Labels by Application Instance

Tags are an effective way for us to distinguish between different instances of the same application. For example, we used SBA to monitor three instances of the spring.application.name=admin-client application: development (DEV), TEST (TEST), and production (PROD). We can do this by (taking development as an example) :

Using message endpoints /info:

info:
  tags:
    environment: DEV
Copy the code

Or configure SBA metadata:

 spring:
       boot:
         admin:
           client:
             instance:
               metadata:
                 tags:
                   environment: DEV 
Copy the code

Then we can view the specific information through the details interface:

5.3 Email Notification

Spring Boot Admin supports configuring mail to send mail notifications so that we can handle system alerts in a timely manner.

Introducing mail dependencies

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-mail</artifactId>
 </dependency>
Copy the code

Spring Boot Mail configuration

# Spring Boot Mail configuration
 spring:
   mail: 
    host: smtp.qq.com
    username: [email protected]
    password: password
    properties:
      mail:
       smtp:
         auth: true
         starttls:
           enable: true
           required: true
Copy the code

Spring Boot Admin mail configuration

 # SBA mail configuration
   boot:
    admin:
     notify:
       mail:
         from: [email protected] 
         to: [email protected]
Copy the code

In this way, you can receive email alarms. The nailing robot notification function can also be used in Korea.

There are other features that you can learn from the official documentation.

6. Summary

Today we learned how to use Spring Boot Admin to monitor Spring Boot applications. You also learned how to do secure access control for Spring Boot Admin, as well as some useful advanced operations. What needs to be explained here is that for some small applications Spring Boot Admin can be fully competent to monitor functions, but also very simple to use. However, I personally do not recommend using Spring Boot Admin for large distributed cluster applications, requiring other more professional APM monitoring, such as the open source Apache Skywalking, Prometheus + Grafana, etc.

relatedSBAActual combat complete code can be concerned about the public number:FelordcnreplyadminTo obtain

Follow our public id: Felordcn for more information

Personal blog: https://felord.cn