Vish
Vish

Reputation: 148

Logging Spring Boot Actuator health status in the application log file

Currently we are using Spring boot actuator vr 1.5.10 and we can access our health page with /health endpoint successfully. But while accessing our health endpoint, we need to log that health status in our application's log file as well so later we can create a Kibana watcher alert based on the status.

I saw that we can extend the health endpoint with "@EndpointWebExtension" and log the status there as proposed in here. But seems like that is not supported with vr 1.5.10.

Any direction will be really appreciated!

Upvotes: 3

Views: 5758

Answers (2)

DwB
DwB

Reputation: 38300

Spring will inject a list of all components that implement a specific interface. For example: private List<HealthIndicator> healthIndicatorList will contain every class that implements the HealthIndicator class.

You could implement the HealthIndicator class in your own component and then call the health() method on each member of the healthIndicatorList and log the result.

Of course, do not recursively call the health() method of your logging health indicator. Here is some code:

@Component
public class LoggingHealthIndicator implements HealthIndicator
{
    @Autowired
    private List<HealthIndicator> healthIndicatorList

    @Override
    public Health health()
    {
        for (final HealthIndicator current : healthIndicatorList)
        {
            if (current != this)
            {
                // assumes SLF4j
                logger.log("blam message; {}", current.health());
            }
        }       
        return Health.up().build();
    }
}

That code might not work because you class wants all HealthIndictor implementations and is a HealthIndicator itself.

You might need to add a @PostConstruct method and retrieve the list of HealthIndictor components yourself.

Upvotes: 2

pL4Gu33
pL4Gu33

Reputation: 2085

You could write your own HealthAggregator and set the Default Spring Aggregator in it and use it.

public class OwnHealthAggregator implements HealthAggregator {

private final HealthAggregator defaultHealth;

public OwnHealthAggregator(HealthAggregator defaultHealth) {
    this.defaultHealth = defaultHealth;
}

@Override
public Health aggregate(Map<String, Health> healths) {
    Health result = this.defaultHealth.aggregate(healths);
    // LOG Result here
    return result;
}

}

Define a bean and use the default one:

@Bean
public HealthAggregator health() {
    return new OwnHealthAggregator(new OrderedHealthAggregator());
}

Off-topic when you use actuator in this version, you should be careful because many endpoints are enable by default (like /beans, /env, /dump).

Upvotes: 2

Related Questions