Changing availability state(readiness/liveness/etc.) is significant events for application. Currently, there is no logging around the availability state change and this makes it hard to find out what caused the state to change when somebody needs to look back what has happened to the application. So, we would like to capture the state change event in application log.

The caller(event publisher) side can log the event but it is more enforced if ApplicationAvailabilityBean(receiver side) logs the event.

For now, state change logging can be achieved by implementing a custom ApplicationListener like followings.

@Slf4j
@Order(0)  // make sure this listener run before "ApplicationAvailabilityBean"
class AvailabilityStateChangeLoggingListener implements ApplicationListener<AvailabilityChangeEvent<?>> {

  private final ApplicationAvailability availability;

  public AvailabilityStateChangeLoggingListener(ApplicationAvailability availability) {
    this.availability = availability;
  }

  @Override
  public void onApplicationEvent(AvailabilityChangeEvent<?> event) {
    AvailabilityState newState = event.getState();
    AvailabilityState lastState = this.availability.getState(newState.getClass());
    if (lastState != null && newState != lastState) {
      Class<? extends AvailabilityState> stateType = getStateType(newState);
      log.info("AvailabilityState changed. type={}, new={}, last={}, source={}",
          stateType.getSimpleName(), newState, lastState, event.getSource().getClass().getSimpleName());
    }
  }

  @SuppressWarnings("unchecked")
  private Class<? extends AvailabilityState> getStateType(AvailabilityState state) {
    if (state instanceof Enum) {
      return (Class<? extends AvailabilityState>) ((Enum<?>) state).getDeclaringClass();
    }
    return state.getClass();
  }

}

But the caveat is this needs to implement @Order/Ordered to ensure the listener ordering correct to retrieve the last state.

If ApplicationAvailabilityBean logs state change, this custom listener is not needed.

Comment From: wilkinsona

Superseded by #23098.