简体   繁体   中英

Spring Boot Actuator - Custom Health Endpoint

I am using SpringBoot Actuator to return health of the app.

public class HealthMonitor implements HealthIndicator {

    @Override
    public Health health() {
        int errorCode = check();
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

    public int check() {
        return 0;
    }

}

I see the below response

{
  "status": "UP",
  "diskSpace": {
    "status": "UP",
    "free": 55020113920,
    "threshold": 10485760
  },
  "db": {
    "status": "UP",
    "database": "Oracle",
    "hello": "Hello"
  }
}

I want to return a response similar to below

{status: "Healthy"}

Is there a way to do it?

To customize your Status message there is one method named: withDetail() . So when you are writing return Health.up().build(); just replace this with

return Health.up().withDetail("My Application Status","Healthy")

So this will give

{My Application Status: "Healthy"}

I don't think you're going to be able to persuade the supplied Spring Boot health endpoint to display in a dramatically different format.

Most of the Spring source code is very clear, and this is no exception. Look at the source for org.springframework.boot.actuate.endpoint.HealthEndpoint and you'll see it has an invoke() method that returns a Health . The JSON you are seeing is Jackson's marshalling of that object.

You could, however, create your own endpoint, extending AbstractEndpoint in exactly the same way as HealthEndpoint does, returning whatever class of your own you like.

You could even make it delegate to the HealthEndpoint bean:

 public MyHealthEndpoint(HealthEndpoint delegate) {
     this.delegate = delegate;
 }

 @Override
 public MyHealth invoke() {
      Health health = delegate.invoke();
      return new MyHealth(health.getStatus());
 }

There is a lot of flexibility with Spring Boot and its health indicators.

First, depending on the complexity of your service, you may not need the HealthIndicator you describe above. Out of the box, Spring Boot will return status' based upon your spring configurations. This includes databases (both SQL and some noSQL), Mail, JMS and others. This is described in the latest Spring Boot documents in section 47.6.1

The easiest way to return what you want, with or without the HealthIndicator class, is to set a property in your application.properties:

endpoints.health.sensitive=true

This may only apply to the later versions (after 1.4?) of Spring Boot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM