⬆️ ⬇️

Introduction to Spring Boot Actuator

Salute, habrovchane! In a week, classes will start in the new group of the Developer on the Spring Framework course. In this regard, we are sharing with you useful material in which it is told about 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. Monitoring applications 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 a business.



Traditionally, before Spring Actuator, we needed to write code to test the functionality of the application, but with Spring Actuator we don’t need to write code. Spring Actuator provides several ready-made endpoints (endpoint) that can be useful for monitoring an application.



How to add Spring Actuator to Maven or Gradle project?



Maven



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


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 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 the SpringActuatorApplication running on Tomcat. You can also see that the actuator endpoints are available at /actuator.



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


Application Monitoring with Spring Actuator Endpoints



As we said above, Spring Actuator provides several ready-made endpoints that we can use to monitor the health of the application.



IDDescription
auditevents

Provides information about events

audit for the current application.

beansDisplays a complete list of all

Spring beans in the application.

cachesCache information

conditionsShows the conditions that

were computed for configuration classes

and autoconfigurations, and reasons for

which they matched or not

matched.

configpropsDisplays a list of all

@ConfigurationProperties

envDisplays properties from

ConfigurableEnvironment.

flywayShows database migrations

Flyway that have been applied.

healthDisplays health information

applications.

httptraceDisplays trace information

HTTP (default is the last 100 HTTP

requests-responses).

infoDisplays additional information

about the application.

integrationgraphSpring Integration graph.

loggersDisplays and allows

change logger configuration in

application.

liquibaseShows applied migrations

Liquibase database.

metricsShows information about metrics

for the current application.

mappingsDisplays a list of all paths.

@RequestMapping.

scheduledtasksDisplays scheduled tasks

(scheduled tasks).

sessionsAllows to retrieve and delete

user sessions from repositories,

Supported Spring Session. Not available

when using spring session for jet

web applications.

shutdownAllows the app to correctly

to finish work.

threaddumpDisplays information about streams.



Enable endpoints



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



 management.endpoint.<code><</code>id<code>></code>.enabled 


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


Example:



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



 management.endpoint.shutdown.enabled=true 


We can disable all endpoints, and then include only those that we need. With the following configuration, all endpoints except info will be disabled.



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


Access to endpoints via HTTP



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



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







As you have noticed, only the health and info endpoints are shown here. 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 web access (http) to other endpoints, then we need to make the following entries in the application.properties file.



 management.endpoints.web.exposure.include=<    ><a href="http://localhost:8080/actuator"></a> 


Example :



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


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



As we can see in the screenshot below, the endpoint env also 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 but one endpoint



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



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










Disable all HTTP endpoints



If you do not want to provide endpoints via HTTP, you can do this by setting the following in the application.properties file:



 management.server.port=-1 


or so:



 management.endpoints.web.exposure.exclude=* 


Setting the URL for accessing the endpoints



By default, all endpoints are accessible by URL /actuator by addresses of the form /actuator/{id} . However, you can change the base path of the /actuator using the following property in the application.properties .



 management.endpoints.web.base-path 


For example, if you want to make a base URL like /monitor instead of /actuator you can do this as follows:



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






All endpoints will be available as /monitor/{id} instead of /actuator/{id}







Spring Boot Actuator Endpoints



Let's discuss some of the most important endpoints.



/ health



The endpoint health gives the overall status of the application: running and running or not. This is very important for monitoring the state 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 health endpoint depends on the management.endpoint.health.show-details property in the application.properties file.



If management.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 displayed 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 state 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 management.endpoint.health.roles property.



Preset Indicators



Spring Boot Actuator has many automatically configured “health indicators” (HeathIndicators) for testing the performance of various parts of the application. For example, DiskspaceHealthIndicator provides disk space information. If you are using MongoDB, then MongoHealthIndicator will check the operability of the Mongo database (whether the server is running or not) and display the relevant information. By default, the final status of the app is determined by HealthAggregator , which 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.



Disable 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 


Disable individual indicator



Alternatively, you can disable a separate HealthIndicator , as shown below, for example, to disable disk space checking:



 management.health.diskspace.enabled=false 


Note: The identifier for any HealthIndicator will be the name of the bean without the suffix HealthIndicator .



For example :



 DiskSpaceHealthIndicator diskspace MongoHealthIndicator mongo CassandraHealthIndicator cassandra DataSourceHealthIndicator datasource 


and so on…



Writing Your Indicators (HealthIndicator)



Along with the built-in HealthIndicator provided by Spring Boot Actuator, we can create our own state indicators. To do this, you need to create a class that implements the HealthIndicator interface, implement its health() method and return Health as a response with the appropriate 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 move on to the health endpoint again and see if our indicator is reflected or not.







We see our indicator.



Individual component status



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



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



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







/ info



The info endpoint provides general information about the application, which it receives from files such as build-info.properties or git.properties , or from the properties specified in application.properties .



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







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



Let's add a build-info target for the spring-boot-maven-plugin to pom.xm l.



 <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.1.0.RELEASE</version> <executions> <execution> <goals> <goal>build-info</goal> </goals> <configuration> <additionalProperties> <encoding.source>UTF-8</encoding.source> <encoding.reporting>UTF-8</encoding.reporting> <java.source>${maven.compiler.source}</java.source> <java.target>${maven.compiler.target}</java.target> </additionalProperties> </configuration> </execution> </executions> </plugin> 


Now let's look at the info endpoint again and see the build information as shown below:







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



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






/ beans



The beans endpoint shows 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 named TestController and injected a component named TestService



 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 configProps shows all bins annotated by @ConfigurationProperties .







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



The screenshot below shows the source code for HttpTraceProperties , annotated by @ConfigurationProperties .







/ env



The env endpoint provides all environmental information in the following order:



System properties

depends on JVM (platform independent)

System environment or variables

surroundings

depends on operating

system (platform dependent)

Application Level Settings

defined in

application.properties







/ heapdump



The heapdump endpoint 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



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



The level property indicates which logging levels are supported by the logging framework.







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



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







/ metrics



The end point metrics shows all the metrics that you can track for your application.







Individual Metric Check



You can view a separate 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



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

Source: https://habr.com/ru/post/452624/



All Articles