Spring Boot Actuator: Health check, audit, statistics, and monitoring

Spring Boot Actuator helps you monitor and manage Spring Boot applications, such as health checks, auditing, statistics, and HTTP tracking. All of these features can be obtained via JMX or HTTP endpoint.

The Actuator can also be integrated with external application monitoring systems such as Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic, etc. These systems provide excellent dashboards, ICONS, analytics, and alerts, making it easy to monitor and manage your applications through a unified interface.

The Actuator uses Micrometer to integrate the external application monitoring systems mentioned above. This makes it possible to integrate any application monitoring system with a very small configuration.

I’m going to break the Spring Boot Actuator tutorial into two parts:

  • Part 1 teaches you how to configure the Actuator and access these features through Http endpoints.
  • The second part teaches you how to integrate actuators with external application monitoring systems.

Create a Spring Boot project with Actuator

First let’s build a simple application that relies on the Actuator. Maven has the following dependencies:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

Use Actuator Endpoints to monitor applications

The Actuator creates so-called endpoints that expose HTTP or JMX to monitor and manage applications.

For example

  • /healthProvides basic information about application health.
  • /metricsThe endpoint shows several useful metrics, such as JVM memory usage, system CPU usage, open files, and so on.
  • /loggerThe endpoint displays application logs and allows you to change the log level at run time.

Note that each actuator endpoint can be displayed on or off. These endpoints also need to be exposed via HTTP or JMX so that they can be accessed remotely.

Let’s run the app and try to enter the open state that is exposed via HTTP by default. Later we’ll learn how to open more EndPoints and expose them over HTTP.

Create an

Let’s start the Actuator app, which runs on port 8080 by default.

Can start after successful, via http://localhost:8080/actuator to display all exposed via HTTP endpoints.

Open the http://localhost:8080/actuator/health, will display the following:

The status will be UP as long as the application is healthy. If the application is unhealthy, the state will be DOWN. For example, the connection to the dashboard is abnormal or the disk space is missing. In the next section, we’ll learn how Spring Boot determines the health of your application and how to fix those health problems.

Info endpoint (http://localhost:8080/actuator/info) shows the general information about the application, the information from the compiled files, such as META info/build – info. The properties, or GIT file, Such as git.properties or any environment’s property. You will learn how to change the output of this endpoint in the next section.

** By default, only health and INFO are exposed via HTTP. ** This is why the /actuator page only displays Health and InfoendPoints. We’ll learn how to expose other endpoints. First, let’s look at what the other endpoints are.

Common actuator EndPoints list

Here is a list of some of the most useful actuator Endpoints. You can see the full list at Official Documentation.

Endpoint ID Description
auditevents Display audit events exposed by the application (such as authentication entry, order failure)
info Basic application information is displayed
health Displays the application health status
metrics Displays measurement information for a variety of applications
loggers Displays and modifies configured loggers
logfile Return the contents of the log file (if logging.file or logging.path is set)
httptrace Displays HTTP footprints, the last 100 HTTP Requests /repsponse
env Displays current environment features
flyway Displays detailed information about the database migration path
liquidbase Displays details about the Liquibase database migration
shutdown Let you gradually shut down the application
mappings Display all @requestMapping paths
scheduledtasks Displays scheduling tasks in the application
threaddump Perform a thread dump
heapdump Returns a Gzip-compressed JVM heap dump

Open and close the Actuator Endpoints

By default, all endPoints mentioned above are open, except shutdownendpoint.

You can set management. Endpoint.. Enabled to true or false (id is the ID of the endpoint) to enable or disable one endpoint.

For example, to turn on shudownendpoint, add the following to your application.properties file:

management.endpoint.shutdown.enabled=true
Copy the code

Exposure to physical Endpoints

By default, all the actuator endpoints are exposed through JMX, while only health and INFO are exposed through HTTP.

  • Exposing endpoints using HTTP.

    # Use "*" to expose all endpoints, or a comma-separated list to expose selected ones
    management.endpoints.web.exposure.include=health,info 
    management.endpoints.web.exposure.exclude=
    Copy the code
  • Exposing endpoints using JMX.

    # Use "*" to expose all endpoints, or a comma-separated list to expose selected ones
    management.endpoints.jmx.exposure.include=*
    management.endpoints.jmx.exposure.exclude=
    Copy the code

By setting the management. The endpoints. Web. Exposure. Include for *, we can see the following content in http://localhost:8080/actuator pages.

{
    "_links": {"self": {"href":"http://localhost:8080/actuator"."templated":false
        },
        "beans": {"href":"http://localhost:8080/actuator/beans"."templated":false
        },
        "caches-cache": {"href":"http://localhost:8080/actuator/caches/{cache}"."templated":true
        },
        "caches": {"href":"http://localhost:8080/actuator/caches"."templated":false
        },
        "health": {"href":"http://localhost:8080/actuator/health"."templated":false
        },
        "health-path": {"href":"http://localhost:8080/actuator/health/{*path}"."templated":true
        },
        "info": {"href":"http://localhost:8080/actuator/info"."templated":false
        },
        "conditions": {"href":"http://localhost:8080/actuator/conditions"."templated":false
        },
        "shutdown": {"href":"http://localhost:8080/actuator/shutdown"."templated":false
        },
        "configprops": {"href":"http://localhost:8080/actuator/configprops"."templated":false
        },
        "env": {"href":"http://localhost:8080/actuator/env"."templated":false
        },
        "env-toMatch": {"href":"http://localhost:8080/actuator/env/{toMatch}"."templated":true
        },
        "loggers": {"href":"http://localhost:8080/actuator/loggers"."templated":false
        },
        "loggers-name": {"href":"http://localhost:8080/actuator/loggers/{name}"."templated":true
        },
        "heapdump": {"href":"http://localhost:8080/actuator/heapdump"."templated":false
        },
        "threaddump": {"href":"http://localhost:8080/actuator/threaddump"."templated":false
        },
        "metrics-requiredMetricName": {"href":"http://localhost:8080/actuator/metrics/{requiredMetricName}"."templated":true
        },
        "metrics": {"href":"http://localhost:8080/actuator/metrics"."templated":false
        },
        "scheduledtasks": {"href":"http://localhost:8080/actuator/scheduledtasks"."templated":false
        },
        "mappings": {"href":"http://localhost:8080/actuator/mappings"."templated":false}}}Copy the code

Parses common actuator endpoints

/health endpoint

/ Health Endpoint Checks the health of applications by merging several health indices.

Spring Boot Actuators have several predefined health metrics, Such as DataSourceHealthIndicator, DiskSpaceHealthIndicator, MongoHealthIndicator, RedisHealthIndicator, CassandraHealthInditor, etc. It uses these health indicators as part of its health check.

For example, if your app uses Redis, RedisHealthIndicator will be considered part of the check. If you use Mongo, then MongoHealthIndicator will be used as part of the check.

You can also turn off specific health check metrics, such as using the following command in Properties:

management.health.mongo.enabled=false
Copy the code

By default, all of these health indicators are considered as part of the examination.

Displays detailed health information

The Health endpoint shows only simple UP and DOWN states.

To get detailed information about all metrics in your health check, you can add the following to application.properties:

management.endpoint.health.show-details=always
Copy the code

Once you turn on the switch, you can see in http://localhost:8080/actuator/health details are as follows:

The Health endpoint now includes the DiskSpaceHealthIndicator.

If your app contains Redis, health EndPoints will display the following:

Create a custom health indicator

You can define a HealthIndicator by implementing the HealthIndicator interface or by inheriting the AbstractHealthIndicatior class.

package com.example.actuator.springbootactuator;

import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        // Use the builder to build the health status details that should be reported.
        // If you throw an exception, the status will be DOWN with the exception message.

        builder.up()
                .withDetail("app"."Alive and Kicking")
                .withDetail("error"."Nothing! I'm good."); }}Copy the code

Once you add the above health metrics to your application, Health EndPoints will display the following details:

/metrics endpoint

The Metrics endpoint shows all the metrics you can track.

Want to get the detailed information for each of the metrics, you need to pass the name of the measure to the URL, like http://localhost:8080/actuator/metrics/ {MetricName}

For example, to get the system. The CPU. The usage of detailed information, use the URL http://localhost:8080/actuator/metrics/system.cpu.usage.

It will display the following:

/loggers endpoint

Loggers endpoint, visit http://localhost:8080/actuator/loggers to enter. He shows a list of configurable Loggers in the application and the associated logging levels.

You can also use http://localhost:8080/actuator/loggers/ to display the details of the particular logger {name}.

For example, in order to obtain the details of the root logger, you can use http://localhost:8080/actuator/loggers/ROOT:

Change the log level at run time

Loggers endpoint also allows you to change the logging level of your application at run time.

For example, in order to change the root logger level to DEBUG, send a POST request to http://localhost:8080/actuator/loggers/ROOT, add the following parameters

{
   "configuredLevel": "DEBUG"
}
Copy the code

This feature is very useful for troubleshooting online problems.

Also, you can reset the log level by passing null to configuredLevel.

/info endpoint

/info Endpoint displays basic application information. It uses meta-INF /build-info.properties to get build information and gits.properties to get git information. It can also display any other information as long as the environment property contains the Info key.

You can add properties to application.properties, for example:

# INFO ENDPOINT CONFIGURATION
[email protected]@
[email protected]@
[email protected]@
[email protected]@
[email protected]@
Copy the code

Note that I used the Automatic Property Expansion feature of Spring Boot to extend the properties from the Maven project.

Once you add the properties above, the info endpoint will display the following information:

Annotation Mode Customize the Endpoint

Write a custom endpoint

@Endpoint(id = "my-endpoint")
public class MyEndpoint {

    @ReadOperation
    public Map<String, Object> endpoint(a) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("Current time:".new Date().toString());
        map.put("message"."this is my endpoint");
        returnmap; }}Copy the code

Writing configuration classes

@Configuration
public class EndpointConfiguration {

    @Bean
    public MyEndpoint endpoint(a) {
        return newMyEndpoint(); }}Copy the code

The results of

Pay attention to

  • @EndPointCan not use the hump method, need to be separated by –
  • Spring Boot will scan it@EndPointUnder the annotation of@ReadOperation.@WriteOperation.@DeleteOperationAnnotations, respectively, corresponding to the generationGet/Post/DeleteThe Mapping. There’s one in the notesproducesParameter to specify the media type, for example:application/jsonAnd so on.

Use Spring Security to ensure Security of Endpoints

Actuator endpoints are sensitive and must ensure that access is authorized. If Spring Security is included in your application, the endpoint is protected through HTTP authentication.

If not, you can add the following dependencies to your application:

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

Let’s look at how to override the Spring Security configuration and define your own entry rules.

The following example shows a simple Spring Security configuration. It uses the RequestMatcher factory mode called EndPointRequest to configure the Actuator Endpoints entry rules.

package com.example.actuator.springbootactuator;

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
                .hasRole("ACTUATOR_ADMIN")
                .requestMatchers(EndpointRequest.toAnyEndpoint())
                .permitAll()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
                .permitAll()
                .antMatchers("/")
                .permitAll()
                .antMatchers("/ * *") .authenticated() .and().httpBasic(); }}Copy the code

To test the above configuration, you can add a Spring Security user to application.propert.

# Spring Security Default user name and password
spring.security.user.name=actuator
spring.security.user.password=actuator
spring.security.user.roles=ACTUATOR_ADMIN
Copy the code

Next part: Prometheus&Grafana for Spring Boot Metrics monitoring

Article source address

Autumn200.com/2020/07/05/…

Translation of the source

  • Spring Boot Actuator metrics monitoring with Prometheus and Grafana