Help Center/ Cloud Application Engine/ FAQs/ Component Configuration FAQs/ How Do I Provide Prometheus Metrics for a Java Application?
Updated on 2024-05-25 GMT+08:00

How Do I Provide Prometheus Metrics for a Java Application?

Context

Prometheus is built in CAE to collect monitoring metrics of components. The default monitoring metrics are limited. To customize more metrics, define the corresponding structure (Exporter) in the program, expose the API, deploy the structure on CAE, and configure it. This section uses the Spring Boot backend component in Getting Started as an example to describe how to customize Prometheus metrics. It exposes Prometheus metrics through HTTP and customizes the metric structure as required.

Adding the POM Dependency

Add the following dependency to the src/pom.xml file.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

Modifying the Configuration File

Modify the actuator configuration in the application.yml file in the resources directory to expose Prometheus metric data.

management:
  endpoints:
    web:
      exposure:
        include: prometheus

After configuration, the Spring Boot project exposes Prometheus monitoring metrics through port 9090 in the /actuator/prometheus path.

Customizing Monitoring Metrics in the Spring Boot Project

Define a metric of the Counter type: The value increases by 1 each time a frontend click calls the backend API.

In src\main\java\com\huawei\cae\controller\UserDataController.java, define the following fields and methods and import required classes:

The function is to define monitoring metric click_operated_total of the Counter type.

import io.micrometer.core.instrument.Counter; 
import io.micrometer.core.instrument.MeterRegistry;
import javax.annotation.PostConstruct;
...

@Autowired 
private MeterRegistry registry; 

private Counter visitCounter; 

@PostConstruct 
private void init() { 
 visitCounter = registry.counter("click_operated_total", "click_operated_total","");
 }

Add the following code to the first line of the clientTest() method called by the frontend:

visitCounter.increment();

In this way, each time the method is accessed, the value of click_ operated_total defined above increases by 1.

The modified project can be deployed on CAE to monitor the customized Prometheus metrics.