CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-springframework-boot--spring-boot-starter-actuator

Spring Boot starter that provides comprehensive production-ready monitoring and management capabilities for applications

Pending
Overview
Eval results
Files

metrics-system.mddocs/

Metrics System

Spring Boot Actuator integrates with Micrometer to provide comprehensive application metrics collection, measurement, and export capabilities. It automatically configures metrics for common application components and supports export to various monitoring systems.

Capabilities

Metrics Endpoint

Primary endpoint for accessing collected application metrics.

/**
 * Endpoint for application metrics
 */
@Endpoint(id = "metrics")
public class MetricsEndpoint {
    
    /**
     * List all available metric names
     * @return response containing all metric names
     */
    @ReadOperation
    public ListNamesResponse listNames() { /* ... */ }
    
    /**
     * Get details for a specific metric
     * @param requiredMetricName the name of the metric
     * @param tag optional tag filters in the format key:value
     * @return the metric response with measurements and metadata
     */
    @ReadOperation
    public MetricResponse metric(@Selector String requiredMetricName,
                                @Nullable List<String> tag) { /* ... */ }
    
    /**
     * Response containing available metric names
     */
    public static final class ListNamesResponse {
        private final Set<String> names;
        
        public Set<String> getNames() { return this.names; }
    }
    
    /**
     * Response containing metric details
     */
    public static final class MetricResponse {
        private final String name;
        private final String description;
        private final String baseUnit;
        private final List<Sample> measurements;
        private final List<AvailableTag> availableTags;
        
        public String getName() { return this.name; }
        public String getDescription() { return this.description; }
        public String getBaseUnit() { return this.baseUnit; }
        public List<Sample> getMeasurements() { return this.measurements; }
        public List<AvailableTag> getAvailableTags() { return this.availableTags; }
    }
    
    /**
     * A single metric measurement sample
     */
    public static final class Sample {
        private final Statistic statistic;
        private final Double value;
        
        public Statistic getStatistic() { return this.statistic; }
        public Double getValue() { return this.value; }
    }
    
    /**
     * Available tag for filtering metrics
     */
    public static final class AvailableTag {
        private final String tag;
        private final Set<String> values;
        
        public String getTag() { return this.tag; }
        public Set<String> getValues() { return this.values; }
    }
}

Automatic Timing Configuration

Configuration for automatic timing of web requests and method calls.

/**
 * Configuration for automatic timing
 */
public final class AutoTimer {
    
    /**
     * AutoTimer that is enabled
     */
    public static final AutoTimer ENABLED = new AutoTimer(true);
    
    /**
     * AutoTimer that is disabled
     */
    public static final AutoTimer DISABLED = new AutoTimer(false);
    
    /**
     * Create a new AutoTimer
     * @param enabled whether timing is enabled
     */
    public AutoTimer(boolean enabled) { /* ... */ }
    
    /**
     * Return whether auto-timing is enabled
     * @return true if enabled
     */
    public boolean isEnabled() { /* ... */ }
}

Prometheus Integration

Endpoints and utilities for Prometheus metrics export.

/**
 * Endpoint for Prometheus metrics scraping
 */
@Endpoint(id = "prometheus", enableByDefault = false)
public class PrometheusScrapeEndpoint {
    
    /**
     * Scrape metrics in Prometheus format
     * @return metrics in Prometheus text format
     */
    @ReadOperation(produces = "text/plain;version=0.0.4;charset=utf-8")
    public String scrape() { /* ... */ }
    
    /**
     * Scrape metrics for specific names
     * @param includedNames names of metrics to include
     * @return filtered metrics in Prometheus format
     */
    @ReadOperation(produces = "text/plain;version=0.0.4;charset=utf-8") 
    public String scrape(@Nullable Set<String> includedNames) { /* ... */ }
}

/**
 * Output format options for Prometheus metrics
 */
public enum PrometheusOutputFormat {
    
    /**
     * Prometheus text format version 0.0.4
     */
    CONTENT_TYPE_004("text/plain;version=0.0.4;charset=utf-8"),
    
    /**
     * OpenMetrics text format version 1.0.0
     */
    CONTENT_TYPE_OPENMETRICS_100("application/openmetrics-text;version=1.0.0;charset=utf-8");
    
    private final String type;
    
    PrometheusOutputFormat(String type) { this.type = type; }
    
    public String getType() { return this.type; }
}

/**
 * Manager for Prometheus push gateway integration
 */
public class PrometheusPushGatewayManager {
    
    /**
     * Create a new push gateway manager
     * @param pushGateway the Prometheus push gateway
     * @param registry the meter registry
     * @param scheduler the task scheduler
     */
    public PrometheusPushGatewayManager(PushGateway pushGateway,
                                       CollectorRegistry registry,
                                       TaskScheduler scheduler) { /* ... */ }
    
    /**
     * Push metrics to the gateway
     */
    public void push() { /* ... */ }
    
    /**
     * Shutdown the push gateway manager
     */
    public void shutdown() { /* ... */ }
}

Cache Metrics

Metrics providers for various caching solutions.

/**
 * Provider for cache meter binders
 */
@FunctionalInterface
public interface CacheMeterBinderProvider<C> {
    
    /**
     * Return a MeterBinder for the given cache
     * @param cache the cache to instrument
     * @param tags additional tags
     * @return the meter binder or null if not supported
     */
    @Nullable
    MeterBinder getMeterBinder(C cache, Iterable<Tag> tags);
}

Database Connection Pool Metrics

Metrics for monitoring database connection pools.

/**
 * Metrics for data source connection pools
 */
public class DataSourcePoolMetrics {
    
    /**
     * Create metrics for a data source
     * @param dataSource the data source
     * @param dataSourceName the data source name
     * @param tags additional tags
     * @return the meter binder
     */
    public static MeterBinder createMeterBinder(DataSource dataSource,
                                               String dataSourceName,
                                               Iterable<Tag> tags) { /* ... */ }
}

/**
 * Metrics for R2DBC connection pools
 */
public class ConnectionPoolMetrics {
    
    /**
     * Create metrics for an R2DBC connection pool
     * @param connectionPool the connection pool
     * @param name the pool name
     * @param tags additional tags
     * @return the meter binder
     */
    public static MeterBinder createMeterBinder(ConnectionPool connectionPool,
                                               String name,
                                               Iterable<Tag> tags) { /* ... */ }
}

Usage Examples

Accessing Metrics via HTTP

# List all available metrics
curl http://localhost:8080/actuator/metrics

# Get JVM memory usage
curl http://localhost:8080/actuator/metrics/jvm.memory.used

# Get HTTP request metrics with tags
curl "http://localhost:8080/actuator/metrics/http.server.requests?tag=status:200&tag=method:GET"

# Get database connection pool metrics
curl http://localhost:8080/actuator/metrics/hikaricp.connections.active

Custom Metrics with Micrometer

@Service
public class BusinessMetricsService {
    
    private final Counter orderCounter;
    private final Timer orderProcessingTimer;
    private final Gauge activeUsersGauge;
    private final DistributionSummary orderValueSummary;
    
    public BusinessMetricsService(MeterRegistry meterRegistry) {
        this.orderCounter = Counter.builder("orders.placed")
            .description("Number of orders placed")
            .tag("type", "business")
            .register(meterRegistry);
            
        this.orderProcessingTimer = Timer.builder("order.processing.time")
            .description("Time taken to process orders")
            .register(meterRegistry);
            
        this.activeUsersGauge = Gauge.builder("users.active")
            .description("Number of active users")
            .register(meterRegistry, this, BusinessMetricsService::getActiveUserCount);
            
        this.orderValueSummary = DistributionSummary.builder("order.value")
            .description("Distribution of order values")
            .baseUnit("USD")
            .register(meterRegistry);
    }
    
    public void recordOrderPlaced(Order order) {
        orderCounter.increment(Tags.of("product", order.getProduct()));
        orderValueSummary.record(order.getValue());
    }
    
    public void recordOrderProcessing(Runnable orderProcessing) {
        orderProcessingTimer.recordCallable(() -> {
            orderProcessing.run();
            return null;
        });
    }
    
    private double getActiveUserCount() {
        // Implementation to get active user count
        return 0.0;
    }
}

Automatic Web Request Timing

@Configuration
public class MetricsConfiguration {
    
    @Bean
    public WebMvcMetricsFilter webMvcMetricsFilter(MeterRegistry registry) {
        return new WebMvcMetricsFilter(registry, 
            new DefaultWebMvcTagsProvider(),
            "http.server.requests",
            AutoTimer.ENABLED);
    }
    
    @Bean
    public TimedAspect timedAspect(MeterRegistry registry) {
        return new TimedAspect(registry);
    }
}

@RestController
public class OrderController {
    
    @Timed(name = "orders.create", description = "Time taken to create order")
    @PostMapping("/orders")
    public ResponseEntity<Order> createOrder(@RequestBody CreateOrderRequest request) {
        // Order creation logic
        return ResponseEntity.ok(order);
    }
}

Custom Health Indicator with Metrics

@Component
public class DatabaseHealthWithMetrics extends AbstractHealthIndicator {
    
    private final DataSource dataSource;
    private final Counter healthCheckCounter;
    private final Timer healthCheckTimer;
    
    public DatabaseHealthWithMetrics(DataSource dataSource, MeterRegistry registry) {
        this.dataSource = dataSource;
        this.healthCheckCounter = Counter.builder("health.check")
            .description("Database health check attempts")
            .tag("component", "database")
            .register(registry);
        this.healthCheckTimer = Timer.builder("health.check.time")
            .description("Database health check duration")
            .tag("component", "database")
            .register(registry);
    }
    
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        healthCheckCounter.increment();
        
        Timer.Sample sample = Timer.start();
        try {
            // Perform health check
            try (Connection connection = dataSource.getConnection()) {
                // Simple query to verify connection
                connection.isValid(1);
                builder.up()
                    .withDetail("database", "available")
                    .withDetail("validationQuery", "connection.isValid(1)");
            }
        } finally {
            sample.stop(healthCheckTimer);
        }
    }
}

Prometheus Configuration

@Configuration
@ConditionalOnProperty(name = "management.metrics.export.prometheus.enabled", 
                       havingValue = "true", matchIfMissing = true)
public class PrometheusConfiguration {
    
    @Bean
    public PrometheusMeterRegistry prometheusMeterRegistry(PrometheusConfig config,
                                                          CollectorRegistry registry,
                                                          Clock clock) {
        return new PrometheusMeterRegistry(config, registry, clock);
    }
    
    @Bean
    @ConditionalOnProperty(name = "management.metrics.export.prometheus.pushgateway.enabled",
                          havingValue = "true")
    public PrometheusPushGatewayManager prometheusPushGatewayManager(
            PrometheusProperties.Pushgateway properties,
            CollectorRegistry registry,
            TaskScheduler scheduler) {
        
        PushGateway pushGateway = new PushGateway(properties.getBaseUrl());
        return new PrometheusPushGatewayManager(pushGateway, registry, scheduler);
    }
}

Cache Metrics Integration

@Configuration
@EnableCaching
public class CacheMetricsConfiguration {
    
    @Bean
    public CacheManager cacheManager(MeterRegistry meterRegistry) {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCacheSpecification("maximumSize=1000,expireAfterWrite=10m");
        
        // Bind cache metrics
        cacheManager.getCacheNames().forEach(cacheName -> {
            Cache cache = cacheManager.getCache(cacheName);
            if (cache instanceof CaffeineCache) {
                CaffeineCacheMetrics.monitor(meterRegistry, 
                    ((CaffeineCache) cache).getNativeCache(), 
                    cacheName);
            }
        });
        
        return cacheManager;
    }
}

Built-in Metrics

Spring Boot automatically provides metrics for:

JVM Metrics

  • jvm.memory.used - JVM memory usage
  • jvm.memory.committed - JVM committed memory
  • jvm.memory.max - JVM maximum memory
  • jvm.gc.pause - Garbage collection pause times
  • jvm.threads.live - Live thread count
  • jvm.classes.loaded - Loaded class count

Web Metrics

  • http.server.requests - HTTP request metrics
  • tomcat.sessions.active.max - Maximum active sessions
  • tomcat.threads.busy - Busy thread count

Database Metrics

  • hikaricp.connections.active - Active database connections
  • hikaricp.connections.idle - Idle database connections
  • hikaricp.connections.pending - Pending database connections

Cache Metrics

  • cache.gets - Cache get operations
  • cache.puts - Cache put operations
  • cache.evictions - Cache evictions
  • cache.size - Cache size

Configuration

Metrics system behavior can be configured through application properties:

# Enable/disable metrics endpoint
management.endpoint.metrics.enabled=true

# Configure Micrometer registry
management.metrics.enable.all=true
management.metrics.enable.jvm=true
management.metrics.enable.system=true
management.metrics.enable.web=true

# Prometheus export configuration
management.metrics.export.prometheus.enabled=true
management.endpoint.prometheus.enabled=true

# Push gateway configuration
management.metrics.export.prometheus.pushgateway.enabled=true
management.metrics.export.prometheus.pushgateway.base-url=http://localhost:9091
management.metrics.export.prometheus.pushgateway.job=spring-boot-app

# Distribution percentiles
management.metrics.distribution.percentiles.http.server.requests=0.5,0.95,0.99
management.metrics.distribution.slo.http.server.requests=50ms,100ms,200ms,500ms

# Tags for all metrics
management.metrics.tags.application=my-app
management.metrics.tags.environment=production

# Web request timing
management.metrics.web.server.request.autotime.enabled=true
management.metrics.web.server.request.autotime.percentiles=0.5,0.95,0.99

# Database metrics
management.metrics.jdbc.datasource-proxy.enabled=true

# Cache metrics
management.metrics.cache.instrument-cache=true

Install with Tessl CLI

npx tessl i tessl/maven-org-springframework-boot--spring-boot-starter-actuator

docs

builtin-endpoints.md

configuration-properties.md

endpoint-framework.md

health-system.md

index.md

metrics-system.md

tile.json