Home > OS >  How to add a label to a target in Prometheus using SpringBoot?
How to add a label to a target in Prometheus using SpringBoot?

Time:11-22

I'm trying to add a label to a target in Prometheus modifying files in SpringBoot.

I tried adding a Prometheus label in Springboot the way below (modifying application.yml in SpringBoot), but it didn't work.

management:
  metrics:
    tags:
      application: ${spring.application.name}
      threadLimitInPrometheus: 40 # This tag didn't work

Could you let me know any way to add a Prometheus label in SpringBoot?

I know there is a way to add a new label to a target modifying prometheus.yml the way below

- target_label: "foo"
  replacement: "bar"

However, I'd like to find ways in SpringBoot, not Prometheus.

Thank you.

CodePudding user response:

There are several ways to define tags.

Common tags could be defined in application.yml

management:
  metrics:
    tags:
      key2: value2

In case it doesn't work make sure that configuration is applied. You can run your service locally and use http://localhost:<port>/actuator/prometheus to check exposed metrics.

As an alternative you can use MeterRegistryCustomizer

@Configuration
public class MeterRegistryConfiguration {

    @Bean
    public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
        return (registry) -> registry.config().commonTags("key2", "value2");
    }
}

If you need to define tags for specific metrics only, use MeterFilter

@Bean
public MeterFilter customMeterFilter() {
    return new MeterFilter() {
        @Override
        public Meter.Id map(Meter.Id id) {
            if (id.getName().contains("name")) {
                return id.withTag(Tag.of("key3", "value3"));
            }
            return id;
        }
    };
}
  • Related