DEV Community

Nitish
Nitish

Posted on

Spring Boot Observability: Real-Time Monitoring with Micrometer and Grafana


Okay, I need to write a technical article about Spring Boot observability with Micrometer and Grafana. The user specified a specific structure, so I should follow that closely. Let me start by understanding the requirements.

First, the title needs to be SEO-friendly and specific. Maybe something like "Spring Boot Observability: Real-Time Monitoring with Micrometer and Grafana". That's clear and includes the main keywords.

The pain points: Developers struggle with monitoring Spring Boot apps in production, lack real-time insights, and have difficulty setting up dashboards. I need to phrase this in two sentences.

Prerequisites: Java 17, Spring Boot 3.x, Docker, Grafana and Prometheus setup, basic Micrometer knowledge. That's three to five bullet points.

Main section: Explaining how to integrate Micrometer, export to Prometheus, and visualize in Grafana. Need a complete code example. Let me outline the steps. Create a Spring Boot app, add Micrometer and Prometheus dependencies, configure properties, create a sample controller with metrics, set up Prometheus and Grafana via Docker Compose, and create a dashboard.

Common mistakes: Three mistakes. Maybe not configuring the actuator endpoints, not registering custom metrics correctly, and incorrect Grafana configuration. For each mistake, explain what's wrong and show the fix.

Summary: Key takeaways about the importance of observability, avoiding common mistakes, and leveraging Grafana for visualization.

Now, let me structure each part. The code examples need to be complete and compilable. For the main code example, a controller with a custom metric. The dependencies in build.gradle or pom.xml. Since the user didn't specify build tool, maybe use Maven as it's common. But wait, the user mentioned "exact code example". Let me check the Spring Boot 3.x setup. The main class is straightforward. The controller should have a counter metric. Also, the application.properties for enabling actuator endpoints.

For common mistakes:

Mistake 1: Not exposing actuator endpoints. The fix is adding management.endpoints.web.exposure.include=prometheus,metrics in properties.

Mistake 2: Incorrect metric registration. Using Metrics.globalRegistry instead of MeterRegistry. Show the wrong code and then the corrected version with @Autowired MeterRegistry.

Mistake 3: Not configuring Grafana data source properly. The fix is ensuring Prometheus URL is correct in Grafana's data source config.

I need to make sure all code snippets have the correct imports. For example, the controller imports io.micrometer.core.instrument.Counter and MeterRegistry.

Also, the Docker Compose file for Prometheus and Grafana. The Prometheus config file needs to target the Spring Boot app. Grafana's default credentials.

Check word count. The article should be between 950-1200 words. Each section needs to be concise but thorough.

Let me start drafting each part step by step, ensuring all rules are followed. No placeholders, all code must be complete. Make sure to use Spring Boot 3.x APIs. For example, in the controller, use @RestController and @GetMapping with Spring Web.

Double-check the Prometheus configuration YAML file. The scrape config should point to localhost:8080/actuator/prometheus.

In the Grafana section, explain importing the dashboard ID 4701, which is the Micrometer dashboard.

For common mistake 2, the incorrect code would be using a global registry without injection, and the fix is using the MeterRegistry bean provided by Spring.

Alright, putting it all together now. Make sure each code block has the correct language tag. Java for Java code, yaml for application.properties and Prometheus config, and text for Docker Compose maybe? Wait, Docker Compose is YAML as well. So all YAML files use yaml tags.

Check that all code is correct. For example, the Maven dependencies for Spring Boot Actuator and Micrometer Registry Prometheus.

Yes, the dependencies would be:


org.springframework.boot
spring-boot-starter-actuator


io.micrometer
micrometer-registry-prometheus

In the application.properties, management.endpoints.web.exposure.include=prometheus,metrics.

The controller code with a counter that increments on each request.

The Prometheus config scrape job.

Docker Compose file with Prometheus and Grafana services, volumes for config and data.

Grafana setup steps: login, add data source, import dashboard.

Common mistakes with code examples showing the wrong and right way.

Finally, the summary with key points.

I think that covers all the requirements. Now, write the article following this structure and content.

Spring Boot Observability: Real-Time Monitoring with Micrometer and Grafana

Production debugging without metrics is like flying blind. This guide solves two critical pain points: instrumenting Spring Boot applications for meaningful metrics collection, and transforming raw data into actionable Grafana dashboards without complex infrastructure.

Prerequisites

  • Java 17+ and Spring Boot 3.x
  • Docker installed for monitoring stack
  • Basic understanding of Micrometer metrics
  • Grafana Cloud account or local installation
  • curl/postman for endpoint testing

Implementing Metrics Export with Micrometer

First, create a new Spring Boot 3.x application with these dependencies:

<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Configure actuator endpoints in application.properties:

# application.properties
management.endpoints.web.exposure.include=health,info,prometheus,metrics
management.metrics.export.prometheus.enabled=true
server.port=8080
Enter fullscreen mode Exit fullscreen mode

Create a controller with custom metrics:

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

    private final Counter orderCounter;

    public OrderController(MeterRegistry registry) {
        this.orderCounter = Counter.builder("orders.total")
                                  .description("Total orders processed")
                                  .register(registry);
    }

    @GetMapping("/order")
    public String placeOrder() {
        orderCounter.increment();
        return "Order placed!";
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the application and verify metrics at http://localhost:8080/actuator/prometheus.

Monitoring Stack Setup

Create a Docker compose file:

# docker-compose.yml
version: '3.8'

services:
  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml

  grafana:
    image: grafana/grafana-enterprise:latest
    ports:
      - "3000:3000"
    volumes:
      - grafana_data:/var/lib/grafana

volumes:
  grafana_data:
Enter fullscreen mode Exit fullscreen mode

Configure Prometheus scraping:

# prometheus.yml
global:
  scrape_interval: 5s

scrape_configs:
  - job_name: 'spring-boot'
    metrics_path: '/actuator/prometheus'
    static_configs:
      - targets: ['host.docker.internal:8080']
Enter fullscreen mode Exit fullscreen mode

Start the stack with docker-compose up -d. Access Prometheus at http://localhost:9090 and Grafana at http://localhost:3000.

Common Mistakes

Mistake 1: Missing Actuator Exposure

Developers enable Micrometer but forget to expose endpoints:

# Wrong configuration
management.endpoints.web.exposure.include=health,info
Enter fullscreen mode Exit fullscreen mode

Fix by including Prometheus endpoint:

# application.properties
management.endpoints.web.exposure.include=health,info,prometheus,metrics
Enter fullscreen mode Exit fullscreen mode

Mistake 2: Manual Metric Registration

Creating metrics without proper Spring integration:

// Wrong approach
Counter counter = Counter.builder("api.calls").register(Metrics.globalRegistry);
Enter fullscreen mode Exit fullscreen mode

Inject MeterRegistry instead:

// Correct implementation
private final Counter apiCounter;

public OrderController(MeterRegistry registry) {
    this.apiCounter = Counter.builder("api.calls")
                            .register(registry);
}
Enter fullscreen mode Exit fullscreen mode

Mistake 3: Grafana Data Source Misconfiguration

Using localhost in Prometheus URL inside Docker:

# Wrong Grafana data source
http://localhost:9090
Enter fullscreen mode Exit fullscreen mode

Use Docker's internal networking:

# Correct configuration
http://prometheus:9090
Enter fullscreen mode Exit fullscreen mode

Summary

  • Micrometer provides standardized metrics collection across JVM applications
  • Proper actuator configuration is crucial for Prometheus scraping
  • Grafana dashboards require correct data source networking in containerized environments

The author publishes Spring Boot starter templates at https://gumroad.com

Top comments (0)