Spring Boot Actuator for Monitoring

Loading

Spring Boot Actuator is a powerful tool for monitoring and managing your Spring Boot application. It provides built-in endpoints to expose operational information about your application, such as health, metrics, environment details, and more. Below is a detailed guide on how to use Spring Boot Actuator for Monitoring.


1. Add Spring Boot Actuator Dependency

To enable Actuator, add the following dependency to your pom.xml (for Maven) or build.gradle (for Gradle).

Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Gradle:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

2. Actuator Endpoints

Actuator provides several built-in endpoints to monitor and interact with your application. By default, only the /actuator/health endpoint is enabled.

Common Endpoints:

  • /actuator/health: Application health information.
  • /actuator/info: Application information (customizable).
  • /actuator/metrics: Application metrics (e.g., memory usage, HTTP requests).
  • /actuator/env: Environment properties.
  • /actuator/loggers: View and configure logging levels.
  • /actuator/beans: List all Spring beans.
  • /actuator/mappings: List all HTTP request mappings.
  • /actuator/threaddump: Thread dump information.
  • /actuator/httptrace: HTTP request traces.

3. Enable and Expose Endpoints

By default, only the /actuator/health endpoint is exposed over HTTP. To expose other endpoints, configure the management.endpoints.web.exposure.include property in your application.properties or application.yml.

Example:

management:
  endpoints:
    web:
      exposure:
        include: "*"  # Expose all endpoints

You can also specify specific endpoints:

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics

4. Customizing Actuator Endpoints

a. Custom Health Indicators

You can create custom health indicators to check the status of specific components (e.g., database, external services).

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // Add custom logic to check health
        boolean isHealthy = checkServiceHealth();
        if (isHealthy) {
            return Health.up().build();
        } else {
            return Health.down().withDetail("Error", "Service is down").build();
        }
    }

    private boolean checkServiceHealth() {
        // Implement health check logic
        return true;
    }
}

b. Custom Info Endpoint

Add custom information to the /actuator/info endpoint.

info:
  app:
    name: My Spring Boot App
    version: 1.0.0
    description: A sample Spring Boot application

Or programmatically:

import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;

@Component
public class CustomInfoContributor implements InfoContributor {

    @Override
    public void contribute(Info.Builder builder) {
        builder.withDetail("customInfo", "This is custom info");
    }
}

5. Securing Actuator Endpoints

Actuator endpoints can expose sensitive information, so it’s important to secure them.

a. Enable Security

Add Spring Security dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

b. Configure Security

Restrict access to Actuator endpoints:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class ActuatorSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/**").hasRole("ADMIN") // Only ADMIN can access Actuator
                .anyRequest().permitAll()
            )
            .httpBasic();
        return http.build();
    }
}

6. Monitoring with Prometheus and Grafana

Spring Boot Actuator integrates with Prometheus and Grafana for advanced monitoring.

a. Add Micrometer Prometheus Dependency

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

b. Expose Prometheus Metrics

The /actuator/prometheus endpoint will expose metrics in a format compatible with Prometheus.

c. Configure Prometheus and Grafana

  • Set up Prometheus to scrape metrics from the /actuator/prometheus endpoint.
  • Use Grafana to visualize the metrics.

7. Custom Metrics

You can create custom metrics using Micrometer.

Example:

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    private final Counter myCounter;

    public MyService(MeterRegistry registry) {
        myCounter = Counter.builder("my.custom.counter")
            .description("Counts custom events")
            .register(registry);
    }

    public void doSomething() {
        myCounter.increment();
    }
}

8. Logging with Actuator

Use the /actuator/loggers endpoint to view and change logging levels dynamically.

Example:

  • View current logging levels: GET /actuator/loggers
  • Change logging level: POST /actuator/loggers/com.example
  {
    "configuredLevel": "DEBUG"
  }

9. Best Practices

  • Limit Exposure: Only expose necessary endpoints in production.
  • Secure Endpoints: Use Spring Security to restrict access.
  • Monitor Health: Regularly check the /actuator/health endpoint.
  • Use Metrics: Integrate with Prometheus and Grafana for advanced monitoring.
  • Customize Info: Add application-specific details to the /actuator/info endpoint.

By leveraging Spring Boot Actuator, you can gain deep insights into your application’s performance, health, and operational metrics. Let me know if you need further assistance!

Leave a Reply

Your email address will not be published. Required fields are marked *