Ali Bassam
Ali Bassam

Reputation: 9959

How to create buckets with Micrometer

My understanding of Micrometer is still fairly small, so I will start by presenting what I'm actually trying to achieve.

Purpose

Example Outcome

What I thought of

The issue with this approach if I'm not mistaken, is the number of counters that must be created, for the past, and for the future.

I was thinking if there could be some kind of a bucket support within Micrometer as in:

I am not sure if I'm looking into the right direction to achieve this. Thanks a lot!

Upvotes: 1

Views: 2875

Answers (1)

Jonatan Ivanov
Jonatan Ivanov

Reputation: 6833

Check the docs and read about dimensionality and Tags: https://micrometer.io/docs/concepts

If I understand your issue correctly, you want counters that has a tag (label) that shows you the month it was accessed, here's an example:

public class TagsDemo {
    private static final SimpleMeterRegistry registry= new SimpleMeterRegistry();

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Counter accessCounter = Counter.builder("accessed")
                    .tag("year", getAccessedYear())
                    .tag("month", getAccessedMonth())
                    .register(registry);
            accessCounter.increment();
        }

        System.out.println(registry.getMetersAsString());
    }

    private static String getAccessedYear() {
        return "202" + (int)(Math.random() * 2); // 2020, 2021
    }

    private static String getAccessedMonth() {
        return "0" + ((int)(Math.random() * 2) + 1); // 01, 02
    }
}

This produces 4 time series (2020-01, 2020-02, 2021-01, 2021-02):

accessed(COUNTER)[month='01', year='2021']; count=1.0
accessed(COUNTER)[month='02', year='2021']; count=3.0
accessed(COUNTER)[month='01', year='2020']; count=4.0
accessed(COUNTER)[month='02', year='2020']; count=2.0

On your backend, you can query (I make up a query language since I don't know your registry):

  • What is the total: sum(accessed)
  • What is the total in 2021: sum(accessed WHERE year=2021)
  • What is the total in 2021-01: sum(accessed WHERE year=2021 AND month=01)

Of course you can add just one tag like .tag("date", getAccessedDate()) (2021-01) and query that: sum(accessed WHERE date=2021-01) but that can prevent you being able to query the year and the month separately.

Upvotes: 6

Related Questions