Actuator & Monitoring

🌿 Spring BootLesson 11Intermediate

Spring Boot Actuator adds production-ready monitoring endpoints to your application with zero code. It exposes health checks, metrics, environment info, thread dumps, and more — integratable with Prometheus and Grafana.

1 Actuator Setup & Endpoints
YAML — Actuator Configuration
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus,loggers,threaddump,env
      base-path: /actuator
  endpoint:
    health:
      show-details: when-authorized   # always | never | when-authorized
  info:
    env:
      enabled: true

# Info endpoint custom data
info:
  app:
    name: ${spring.application.name}
    version: ${app.version}
    java-version: ${java.version}
2 Custom Health Indicator
Java — Custom Health Check
@Component
public class ExternalApiHealthIndicator implements HealthIndicator {

    private final RestTemplate restTemplate;

    @Override
    public Health health() {
        try {
            ResponseEntity<String> response =
                restTemplate.getForEntity("https://external-api.com/ping", String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                return Health.up()
                    .withDetail("external-api", "Available")
                    .withDetail("status", response.getStatusCode())
                    .build();
            }
        } catch (Exception ex) {
            return Health.down()
                .withDetail("external-api", "Unavailable")
                .withException(ex)
                .build();
        }
        return Health.unknown().build();
    }
}

// Result at GET /actuator/health:
// {
//   "status": "UP",
//   "components": {
//     "db": { "status": "UP" },
//     "externalApi": { "status": "UP", "details": {...} }
//   }
// }
3 Code Challenge
Challenge: Add micrometer-registry-prometheus to your project and configure Prometheus scraping at /actuator/prometheus. Create a custom counter metric that tracks the number of API requests per endpoint using MeterRegistry.