Search code examples
javaspring-bootstatsdtelegrafmicrometer

How to use Micrometer for metrics collection on TICK stack without using Spring or Spring Boot?


I am writing an app in pure Java without using Spring/SpringBoot or any other frameworks. I am using the TICK stack (Telegraf, Influx, Chronograf, and Kapacitor) as my metrics backend and viz platform. I am using Telegraf with Statsd plugin activated on localhost 8125. The problem is that my app is not sending any metrics to the system. However, I wrote a simple Spring Boot app which pushed the relevant metrics to my dashboard. Also, doing an echo "api.msgs.ok:10|c" | nc -C -w 1 -u localhost 8125 pushes the metrics to my dashboard as well.

The sample code I am trying to run is here:

import io.micrometer.statsd.StatsdConfig;
import io.micrometer.statsd.StatsdFlavor;
import io.micrometer.statsd.StatsdMeterRegistry;


import java.util.Properties;

public class TestMicrometer {


    public static void main(String[] args) throws InterruptedException{
        Properties properties = new Properties();
        //properties.put("statsd.host","127.0.0.1");
        //properties.put("statsd.port","8125");
        StatsdConfig config = new StatsdConfig() {
            //Will use localhost 8125 if get returns null always
            @Override
            public String get(String k) {
                /*
                System.out.println("Key " +k+ " is called");
                if (k.equals("statsd.host")){
                    System.out.println("The host is "+properties.getProperty(k));
                }
                return properties.getProperty(k);

                 */
                return null;
            }
            @Override
            public StatsdFlavor flavor() {
                return StatsdFlavor.TELEGRAF;
            }

        };
        MeterRegistry registry = new StatsdMeterRegistry(config, Clock.SYSTEM);
        Counter.builder("loop.counter.test").description("TOTAL_LOOP_COUNTER").tags("LOOP.COUNTER","SAMPLE.LOOP.METER").register(registry).increment();
        Metrics.addRegistry(registry);
        for (int i = 0; i < 50; i++) {
            Metrics.counter("loop.counter.test").increment();
        }
    }
}

Any help will be highly appreciated :)


Solution

  • Publishing of StatsD metrics is asynchronous, and this example simply terminates too quickly. Put a Thread.sleep(1000) at the end, and metrics are published fine.