Search code examples
endpointspring-boot-actuatorhealth-monitoring

How to extend existing actuator health check endpoint?


There are existing actuator health endpoints, such as:

/actuator/health

How would I extend this existing endpoint to say:

/actuator/health/myendpoint

in order to perform some health check?

Current code:

package com.example.actuatordemo.health;

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", "Testing endpoint extension!")
                .withDetail("error", "Oops.");
    }
}

Solution

  • In order to extend the /health endpoint, you have to implement the HealthIndicator interface like so. In this example, the customized HealthService returns a map of the desired values you want to add to the health endpoint.

      import com.metavera.tako.fc.service.HealthService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.actuate.health.*;
      import org.springframework.stereotype.Component;
    
      import java.util.Map;
    
    
      @Component
      public class HealthCheck implements HealthIndicator {
    
      @Autowired
      HealthService healthService;
    
    
      @Override
      public Health health() {
          return myCustomHealth();
      }
    
      private Health myCustomHealth() {
          Health.Builder builder = new Health.Builder(Status.UP);
          Map<String, Object> response = healthService.getHealthStatus();
    
          for (Map.Entry<String, Object> entry : response.entrySet()) {
              String key = entry.getKey();
              Object value = response.get(key);
              builder.withDetail(key, value);
          }
          return builder.build();
      }
    }
    

    While the above solution allows you to modify the existing /health endpoint, there is additional documentation on how to create custom endpoints here under section 53.7.

    https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html

    Although this is not limited to just health check operations.