Log metrics in Springboot applicaiton using LoggingMeterRegistry

281 views Asked by At

I have some metrics being created in my springboot application and want to log the details of the metrics in a specific format as below: 2018-07-06 17:00:28,884 [metrics-logger-reporter-thread-1] [INFO] (com.codahale.metrics.Slf4jReporter) type=METER, name=io.dropwizard.jetty.MutableServletContextHandler.async-timeouts, count=0, mean_rate=0.0, m1=0.0, m5=0.0, m15=0.0, rate_unit=events/second

I'm currently using LoggingMeterRegistry to log my metrics but the format they get printed it is:system.cpu.usage{} value=0.041922","logger_name":"io.micrometer.core.instrument.logging.LoggingMeterRegistry"

I know that the required format can be achieved through codahale.dropwizard metrics but i want the same using LoggingMeterRegistry from "micrometer" since thats what i am using to calculate my other metrics.

Any help?

1

There are 1 answers

0
A4L On

While asking an own question regarding LoggingMeterRegistry I got suggested this one, which neither helped me nor was answered. So I will try to answer it for future searches.

In order to customize the format of metric logging one could extends LoggingMeterRegistry and override the publish() method. There all meters can retrieved, iterated over, formatted then published. Below is a variant of how it could be done. Of course one could choose to publish all meters at once in which case formatting should be done first, then publishin last.

public class CustomLoggingMeterRegistry extends LoggingMeterRegistry {

  private final LoggingRegistryConfig config;
  private final Consumer<String> loggingSink;

  public CustomLoggingMeterRegistry(
      @NotNull LoggingRegistryConfig config,
      @NotNull Consumer<String> loggingSink) {
    super(Objects.requireNonNull(config),
        Clock.SYSTEM,
        Objects.requireNonNull(loggingSink));
    this.config = config;
    this.loggingSink = loggingSink;
  }


  @Override
  protected void publish() {
    if (config.enabled()) {
      getMeters()
          .stream()
          .sorted(Comparator
              .comparing((Meter m) -> m.getId().getType())
              .thenComparing(m -> m.getId().getName()))
          .forEach(meter -> meter.use(
              this::formatAndPublish,
              this::formatAndPublish,
              this::formatAndPublish,
              this::formatAndPublish,
              this::formatAndPublish,
              this::formatAndPublish,
              this::formatAndPublish,
              this::formatAndPublish,
              this::formatAndPublish));
    }
  }

  private void formatAndPublish(Meter otherMeter) {
    String formatterd = "// TODO format otherMeter as desired";
    this.loggingSink.accept(formatterd);
  }

  // A formatAndPublish for each Meter concrete type ...

}