Skip to content

Application metric

Somkiat Puisungnoen edited this page Nov 18, 2022 · 11 revisions

Application metric with Spring Boot

Step for Application metric

1. Add dependency to file pom.xml

  • Actuator
  • Micrometer + Prometheus
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

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

2. Expose prometheus via Management endpoint for web in file application.properties

  • Healthcheck
  • Info
  • Prometheus
management.info.env.enabled=true
info.app.name=My demo service
info.app.description=My demo service description
info.app.version=1.0.0
management.endpoints.web.exposure.include=health,info,prometheus

3. Start the spring boot server

{
  "_links": {
    "self": {
      "href": "http://localhost:8080/actuator",
      "templated": false
    },
    "health-path": {
      "href": "http://localhost:8080/actuator/health/{*path}",
      "templated": true
    },
    "health": {
      "href": "http://localhost:8080/actuator/health",
      "templated": false
    },
    "info": {
      "href": "http://localhost:8080/actuator/info",
      "templated": false
    },
    "prometheus": {
      "href": "http://localhost:8080/actuator/prometheus",
      "templated": false
    }
  }
}

4. Custom metric in your app with Micrometer

DemoMetricController.java

@RestController
public class DemoMetricController {

    @Autowired
    private MeterRegistry meterRegistry;

    @GetMapping("/count/{message}")
    public ResponseEntity<String> count(@PathVariable String message) {
        if("success".equals(message)) {
            generateMetric("success");
            return new ResponseEntity<>("Success", HttpStatus.OK);
        } else if("notfound".equals(message)) {
            generateMetric("notfound");
            return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND);
        }
        generateMetric("error");
        return new ResponseEntity<>("Error", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    private void generateMetric(String success) {
        Counter counter = Counter
                .builder("hello-springboot")
                .description("Success case")
                .tag("result", success)
                .register(meterRegistry);
        counter.increment();
    }

}

Try to call API

5. Download and Start Prometheus Server

Config file prometheus.yml

scrape_configs:
  - job_name: 'demo-service'
    scrape_interval: 5s
    metrics_path: '/actuator/prometheus'
    static_configs:
      - targets: ['localhost:8080']

Start prometheus server

Reload prometheus

Start server

$./prometheus --web.enable-lifecycle

Reload

$curl -i -XPOST localhost:9090/-/reload