Introduction to Spring Boot Actuator

Original author: Gaurav Bhardwaj
  • Transfer
Salute, Khabrovites! In a week, classes will begin in the new group of the course "Developer on the Spring Framework" . In this regard, we share with you useful material which tells what Spring Actuator is and how it can be useful.



  1. What is Spring Actuator?
  2. How to add Spring Actuator to Maven or Gradle project?
  3. Create a Spring Boot project with a Spring Actuator dependency.
  4. Application Monitoring with Spring Actuator Endpoints.

What is Spring Actuator?

After you have developed the application and deployed it in production, it is very important to monitor its performance. This is especially true for mission-critical applications, such as banking systems, in which application failure directly affects the business.

Traditionally, before the Spring Actuator, we needed to write code to test the health of the application, but with Spring Actuator we did not need to write code. Spring Actuator provides several endpoints that can be useful for monitoring the application.

How to add Spring Actuator to Maven or Gradle project?

Maven

org.springframework.bootspring-boot-starter-actuator

Gradle

dependencies {
  compile("org.springframework.boot:spring-boot-starter-actuator")
}

Creating a Spring Boot project with Spring Actuator

Let's go ahead and create a Spring Boot project with Spring Actuator, Web, and DevTools dependencies using the Spring Initializer .

Please note that at the time of this writing, the Spring Boot version was 2.1.0.



Import the project into Eclipse or any other IDE and run SpringActuatorApplication.java.

In the console, you will see the following: You



can see that the built-in Tomcat is running on port 8080, and SpringActuatorApplicationrunning on Tomcat. You can also see that the actuator endpoints are available at/actuator.

018-11-09 20:00:29.346  INFO 8338 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-09 20:00:29.354  INFO 8338 --- [  restartedMain] n.b.j.s.SpringActuatorApplication        : Started SpringActuatorApplication in 9.273 seconds (JVM running for 11.823)
2018-11-09 20:00:29.190  INFO 8338 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'.

Application Monitoring with Spring Actuator Endpoints

As we said above, Spring Actuator provides several endpoints that we can use to monitor application health.

IDDescription
auditevents
Provides information about
audit events for the current application.
beansDisplays a complete list of all
Spring beans in the application.
cachesCache information.
conditionsShows the Condition that
was calculated for the configuration
and auto- configuration classes , and the reasons
why they met or did not
match.
configpropsDisplays a list of all
@ConfigurationProperties
envDisplays properties from
ConfigurableEnvironment.
flywayShows the migrations of the
Flyway databases that have been applied.
healthShows
application health information .
httptraceDisplays
HTTP trace information (by default, the last 100 HTTP
response requests).
infoDisplays additional information
about the application.
integrationgraphCount Spring Integration.
loggersDisplays and allows you to
change the configuration of loggers in the
application.
liquibaseShows the applied
Liquibase database migrations.
metricsShows metric information
for the current application.
mappingsDisplays a list of all
@RequestMapping paths .
scheduledtasksDisplays
scheduled tasks.
sessionsAllows you to retrieve and delete
user sessions from repositories
supported by Spring Session. Not available
when using Spring Session for reactive
web applications.
shutdownAllows an application
to shut down correctly .
threaddumpDisplays stream information.

Enabling endpoints

By default, all endpoints are enabled except shutdown. To enable the endpoint, use the following property in the file application.properties.

management.endpoint.<id>.enabled

Translator's note: by default, access to all endpoints is only through JMX, there is no access via HTTP to all endpoints (see below).

Example:

To enable the endpoint shutdown, we need to make the following entry in the file application.properties:

management.endpoint.shutdown.enabled=true

We can disable all endpoints and then include only those that we need. In the next configuration, all endpoints except infowill be disabled.

management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true

Accessing Endpoints via HTTP

Let's go to the localhost URL : 8080 / actuator and look at the available endpoints.

Note: I use Postman for testing since it shows JSON in a well-structured format. You can use any other tool or just a browser.



As you already noticed, only the end points healthand are shown here info. Because these are the only endpoints that are accessible by default via http. Access via http to other endpoints is closed by default for security reasons, as they may contain confidential information and, therefore, may be compromised.

Access to specific endpoints

If we want to provide access via web (http) to other endpoints then we need to make the following entries in the file application.properties.

management.endpoints.web.exposure.include=<список конечных точек через запятую>

An example :

management.endpoints.web.exposure.include= health,info,env

Now, after adding the application.propertiesentry in the above record, let's go again to http: // localhost: 8080 / actuator

As we see in the screenshot below, the endpoint is envalso included.



Access to all endpoints

If we want to include all endpoints, we can use the sign *as shown below.

management.endpoints.web.exposure.include=*



Access to all endpoints, except for some. The

two entries below activate all endpoints, but disable the env endpoint.

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env





Disabling all HTTP endpoints

If you do not want to provide endpoints via HTTP, you can do this by setting theapplication.propertiesfollowingin the file:

management.server.port=-1

or so:

management.endpoints.web.exposure.exclude=*

Configuring URLs for Access to Endpoints

By default, all endpoints are accessible by URL/actuatorat view addresses/actuator/{id}. However, you can change the base path/actuatorusing the following property inapplication.properties.

management.endpoints.web.base-path

For example, if you want to make the base URL as /monitorinstead, /actuatoryou can do this as follows:

management.endpoints.web.base-path=/monitor



In this case, all endpoints will be available /monitor/{id}instead of /actuator/{id}



Spring Boot Actuator

Endpoints. Let's discuss some of the most important endpoints.

/ health

The endpoint healthgives the general status of the application: is it up and running or not. This is very important for monitoring the status of the application when it is in production. This endpoint can be integrated with monitoring applications and will be very useful for determining the health of applications in real time.

The amount of information provided by the endpoint healthdepends on the property management.endpoint.health.show-detailsin the file application.properties.

Ifmanagement.endpoint.health.show-details=never, then no additional information is displayed. In this case, you will only see the following (this is the default behavior).



If management.endpoint.health.show-details=always, then additional information is shown to all users. As we see in the answer below, we have information about disk space (diskSpace). If your application is connected to a database, then you will also see information about the status of the database.



If management.endpoint.health.show-details=when-authorized, then additional information will be shown only to authorized users. Authorization can be configured using the property management.endpoint.health.roles.

Preset Indicators The

Spring Boot Actuator has many automatically configured “health indicators” (HeathIndicators) to test the health of various parts of the application. For instance,DiskspaceHealthIndicatorprovides disk space information. If you are using MongoDB, then you MongoHealthIndicatorwill check the Mongo database (whether the server is running or not) and displays the relevant information. By default, the final status of the application determines HealthAggregatorwhich simply sorts the list of statuses provided by each HealthIndicator. The first status in the sorted list is used as the final status of the application.

Disabling all preset indicators

The “health indicators” described above are enabled by default, however, they can be disabled using the following property:

management.health.defaults.enabled=false

Disabling a separate indicator

As an alternative, you can disable a separate indicatorHealthIndicator , as shown below, for example, to disable disk space check:

management.health.diskspace.enabled=false

Note: the identifier of any HealthIndicatorwill be the name of the bean without a suffix HealthIndicator.

For example :

DiskSpaceHealthIndicator	diskspace
MongoHealthIndicator		mongo
CassandraHealthIndicator	cassandra
DataSourceHealthIndicator	datasource

and so on ...

Writing our own indicators (HealthIndicator)

Along with the built-in ones HealthIndicatorprovided by the Spring Boot Actuator, we can create our own status indicators. To do this, you need to create a class that implements the interface HealthIndicator, implement its method health()and return Healthas an answer with the relevant information, as shown below:

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class CustomHealthIndicator implements HealthIndicator {
 @Override
 public Health health() {
  int errorCode = 0; 
  // In the above line,I am simple assigning zero,but you can call Health check related code like below commented line and that method can return the appropriate code.
  // int errorCode = performHealthCheck();
  if (errorCode != 0) {
   return Health.down().withDetail("Error Code", errorCode).build();
  }
  return Health.up().build();
 }
}

Let's go to the health endpoint again and see if our indicator is reflected or not.



We see our indicator.

Status of an individual component

You can also check the status of an individual component. In the above example, we saw the indicator we wrote and diskSpace.

If we want to see only the state of the disk, we can use the following URL:

http: // localhost: 8080 / actuator / health / diskSpace



/ info

The endpoint infoprovides general information about the application that it receives from files, such as build-info.propertiesor git.properties, or from properties referred to in application.properties.

Since there is no such file in our project, the answer will be empty, as shown below:



Spring Boot Actuator displays assembly information if a file is present META-INF/build-info.properties. This project information file is created by the build time goal build-info. Here you can also add an arbitrary number of additional properties.

Let's add a pom.xmtarget build-infofor the plugin to l spring-boot-maven-plugin.

org.springframework.bootspring-boot-maven-plugin2.1.0.RELEASEbuild-infoUTF-8UTF-8${maven.compiler.source}${maven.compiler.target}

Now let's look at the endpoint again infoand see the assembly information, as shown below:



In addition, we can add the application information with the key infoin application.properties, as shown below, and it will be displayed at the endpoint /info.

info.application.name=spring-actuator
info.application.description=spring boot actuator application
info.application.version=0.0.1-SNAPSHOT



/ beans

The endpointbeansshows all the beans defined in the Spring container with the following information about each bean:

aliases  : названия всех псевдонимов
scope   : область видимости
type      : полное имя бина
resource : ресурс (класс), в котором определён бин
dependencies : имена зависимых бинов

For example, I created a RestController with a name TestControllerand injected a component with a nameTestService

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
 @Autowired
 private TestService testService;
 @GetMapping("/messages")
 public String getMessage() {
  return "Hello";
 }
}
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestService {
}

You can see how this is shown for testController in the screenshot below.



/ configprops
The endpoint configPropsshows all beans annotated @ConfigurationProperties.



In the above screenshot, we see two bins that are defined in the Spring Framework itself and are annotated @ConfigurationPropertiesand therefore displayed at this endpoint.

The screenshot below shows the source code HttpTracePropertiesannotated @ConfigurationProperties.



/ env

The endpoint envprovides all the environmental information in the following order:

Properties of the system
JVM dependent (platform independent)
System environment or
environment variables
зависит от операционной
системы (зависит от платформы)
Настройки уровня приложения
определены в
application.properties



/ heapdump

The endpoint of heapdump dumps the application heap. This endpoint returns binary data in HPROF format. Since a lot of data is usually returned, you must save and analyze it.

/ loggers

The endpointloggersprovides application loggers with information about their configured log level (configuredLevel) and effective level (effectiveLevel). If the configured level is not specified for the logger and its parent (null), then the root logger level will be an effective level.

The propertylevelindicates which logging levels are supported by the logging framework.



To get information for a specific logger, pass the name (id) of the logger in the URL after the endpoint/loggers, as shown below:

http: // localhost: 8080 / actuator / loggers / nl.blogpsot.javasolutionsguide.springactuator.SpringActuatorApplication



/ metrics

The endpoint metricsshows all the metrics that you can track for your application.



Verifying an individual metric

You can look at an individual metric by passing it in the URL after /metrics, as shown below:

http: // localhost: 8080 / actuator / metrics / jvm.memory.used



Links

docs.spring.io/spring-boot/docs /current/reference/html/production-ready-endpoints.html
docs.spring.io/spring-boot/docs/current/actuator-api/html

According to the established tradition, we are waiting for your comments and invite everyone to the open day , which will be held 23 May.

Also popular now: