### Full Observation Convention Example Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-handler.adoc Demonstrates the complete setup of an instrumentation using an ObservationConvention, including overriding default tags. ```java Observation.createNotStarted("my-operation", registry) .contextualName("my-contextual-name") .convention(new MyConvention()) .observe(() -> { // ... code to be observed ... }); ``` -------------------------------- ### Setup Micrometer Tracing with Brave Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-api.adoc Provides an example of setting up Micrometer Tracing using Brave components. This configuration is intended to send completed spans to Zipkin. ```java final Tracer tracer = BraveTracer.builder(Tracing.newBuilder().build()).build(); ``` -------------------------------- ### Build Project Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/README.md Run this command to build the project. Ensure dependencies are installed first by running 'yarn install'. ```bash ./gradlew build (or yarn build) ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/README.md Command to install frontend dependencies required for building the project. ```bash ./gradlew installFrontend ``` -------------------------------- ### Timer Builder Example Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/timers.adoc Demonstrates how to create and configure a Timer using its fluent builder API. ```java Timer timer = Timer .builder("my.timer") .description("a description of what this timer does") // optional .tags("region", "test") // optional .register(registry); ``` -------------------------------- ### Setup Micrometer Tracing with OpenTelemetry Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-api.adoc Demonstrates how to set up Micrometer Tracing with OpenTelemetry (OTel) components. This setup is designed to send completed spans to Zipkin. ```java final Tracer tracer = OpenTelemetryTracer.builder(Tracing.newBuilder().build()).build(); ``` -------------------------------- ### Micrometer Observation API Example Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-introduction.adoc This snippet demonstrates the usage of the Micrometer Observation API, including starting an observation, handling potential errors, and managing its scope. ```java import io.micrometer.common.KeyValues; import io.micrometer.common.lang.Nullable; import io.micrometer.observation.*; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; class ObservationTestingTests { @Test void example() { // tag::example[] ObservationRegistry observationRegistry = ObservationRegistry.create(); observationRegistry.observationConfig().observationHandler(new MyCustomObservationHandler()); Observation observation = Observation.createNotStarted("my-observation", observationRegistry) .contextualName("my-contextual-name") .lowCardinality("my-low-cardinality-key", "my-low-cardinality-value") .highCardinality("my-high-cardinality-key", "my-high-cardinality-value") .addKeyValues(KeyValues.of("another-key", "another-value")) .start(); try { // do some work Thread.sleep(100); observation.event(Observation.Event.of("my-event", "my-event-value")); // end::example[] assertThat(observation.getContext().getLowCardinalityKey("my-low-cardinality-key")).isEqualTo("my-low-cardinality-value"); assertThat(observation.getContext().getHighCardinalityKey("my-high-cardinality-key")).isEqualTo("my-high-cardinality-value"); assertThat(observation.getContext().getEvents()).hasSize(1); assertThat(observation.getContext().getEvents().get(0).getValue()).isEqualTo("my-event-value"); } catch (Exception e) { observation.error(e); } finally { observation.stop(); } } static class MyCustomObservationHandler implements ObservationHandler { private final AtomicReference> lowCardinality = new AtomicReference<>(Collections.emptyMap()); private final AtomicReference> highCardinality = new AtomicReference<>(Collections.emptyMap()); private final AtomicReference keyValues = new AtomicReference<>(KeyValues.empty()); private final AtomicReference event = new AtomicReference<>(); @Override public void onStart(Observation.Context ctx) { this.lowCardinality.set(ctx.getLowCardinalityKeys()); this.highCardinality.set(ctx.getHighCardinalityKeys()); this.keyValues.set(ctx.getKeyValues()); } @Override public void onStop(Observation.Context ctx) { // NO-OP } @Override public void onError(Observation.Context ctx) { // NO-OP } @Override public void onEvent(Observation.Event event, Observation.Context ctx) { this.event.set(event); } @Override public boolean supportsContext(Observation.Context context) { return true; } public Map getLowCardinality() { return lowCardinality.get(); } public Map getHighCardinality() { return highCardinality.get(); } public KeyValues getKeyValues() { return keyValues.get(); } @Nullable public Observation.Event getEvent() { return event.get(); } } } ``` -------------------------------- ### Record Metrics with Timer.Sample Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-handler.adoc Store the start state in a Timer.Sample instance and stop it when the event has ended to record measurements. ```java Timer.Sample sample = Timer.start(registry); try { // ... code to be timed ... } finally { sample.stop(timer); } ``` -------------------------------- ### Create a SimpleMeterRegistry Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/registry.adoc Instantiate a SimpleMeterRegistry for in-memory metric storage. This is useful for getting started or when a specific monitoring system is not yet configured. ```java MeterRegistry registry = new SimpleMeterRegistry(); ``` -------------------------------- ### Using Timer.Sample for Manual Timing Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/timers.adoc Illustrates how to manually start a timer sample, execute code, and stop the sample to record the duration. ```java Timer.Sample sample = Timer.start(registry); // do stuff Response response = ... sample.stop(registry.timer("my.timer", "response", response.status())); ``` -------------------------------- ### Example Service with @Timed Annotation Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/timers.adoc Demonstrates applying the @Timed annotation to methods for automatic timing. ```java @Service public class ExampleService { @Timed public void sync() { // @Timed will record the execution time of this method, // from the start and until it exits normally or exceptionally. ... } @Async @Timed ``` -------------------------------- ### Example Timer Creation with @MeterTag (toString) Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/timers.adoc Demonstrates how timers are created when @MeterTag uses the toString() representation of a parameter. ```java include::../../../samples/src/test/java/io/micrometer/docs/metrics/TimedAspectTest.java[tags=example_value_to_string,indent=0] ``` -------------------------------- ### Generated Metrics Documentation Example Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-docs-gen.adoc Example of an Asciidoctor file generated for observability metrics, detailing metric names, types, base units, and tags. ```adoc [[observability-metrics]] === Observability - Metrics Below you can find a list of all samples declared by this project. [[observability-metrics-task-runner-observation]] ==== Task Runner Observation > Observation created when a task runner is executed. **Metric name** `spring.cloud.task.runner` (defined by convention class `org.springframework.cloud.task.configuration.observation.DefaultTaskObservationConvention`). **Type** `timer` and **base unit** `seconds`. Fully qualified name of the enclosing class `org.springframework.cloud.task.configuration.observation.TaskDocumentedObservation`. IMPORTANT: All tags must be prefixed with `spring.cloud.task` prefix! .Low cardinality Keys |=== |Name | Description |`spring.cloud.task.runner.bean-name`|Name of the bean that was executed by Spring Cloud Task. |=== ``` -------------------------------- ### Example Production Code for Observation Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-testing.adoc This Java code demonstrates creating an observation with tags and executing the observe method. ```java public class Example { private final ObservationRegistry observationRegistry; public Example(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } public void doSomething() { Observation.createNotStarted("doSomething", observationRegistry) .tag("low", "value") .tag("high", "value") .observe(() -> { // business logic }); } } ``` -------------------------------- ### Registering a Timer Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/naming.adoc Example of registering a timer with a standard Micrometer naming convention. ```java registry.timer("http.server.requests"); ``` -------------------------------- ### Generated Spans Documentation Example Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-docs-gen.adoc Example of an Asciidoctor file generated for observability spans, detailing span names, conventions, and tag keys. ```adoc [[observability-spans]] === Observability - Spans Below you can find a list of all spans declared by this project. [[observability-spans-task-runner-observation]] ==== Task Runner Observation Span > Observation created when a task runner is executed. **Span name** `spring.cloud.task.runner` (defined by convention class `org.springframework.cloud.task.configuration.observation.DefaultTaskObservationConvention`). Fully qualified name of the enclosing class `org.springframework.cloud.task.configuration.observation.TaskDocumentedObservation`. IMPORTANT: All tags and event names must be prefixed with `spring.cloud.task` prefix! .Tag Keys |=== |Name | Description |`spring.cloud.task.runner.bean-name`|Name of the bean that was executed by Spring Cloud Task. |=== ``` -------------------------------- ### Whitelist HTTP Metrics with Chained Filters Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/meter-filters.adoc Chain MeterFilter instances to create a whitelist. This example accepts meters starting with 'http' and then denies all others. ```java registry.config() .meterFilter(MeterFilter.acceptNameStartsWith("http")) .meterFilter(MeterFilter.deny()); <1> ``` -------------------------------- ### Gradle Build for Micrometer Docs Generator Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-docs-gen.adoc Example Gradle build.gradle configuration for integrating the Micrometer Docs Generator project. ```groovy include::../../../samples/src/test/resources/docs-generator-build.gradle[indent=0,tag=main] ``` -------------------------------- ### Configure Graphite Instance Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/graphite.adoc Example of configuring a Graphite instance programmatically using GraphiteConfig. Useful for direct integration in Java applications. ```java GraphiteConfig graphiteConfig = new GraphiteConfig() { @Override public String host() { return "mygraphitehost"; } @Override public String get(String k) { return null; // accept the rest of the defaults } }; MeterRegistry registry = new GraphiteMeterRegistry(graphiteConfig, Clock.SYSTEM, HierarchicalNameMapper.DEFAULT); ``` -------------------------------- ### Simplified Dynatrace Auto-Configuration (Micrometer 1.10.0+) Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/dynatrace.adoc For Micrometer versions 1.10.0 and above, this simplified code achieves the same auto-configuration as the previous example, reducing boilerplate. ```java MeterRegistry registry = new DynatraceMeterRegistry(DynatraceConfig.DEFAULT, Clock.SYSTEM); ``` -------------------------------- ### Example Timer Creation with @MeterTag (ValueResolver) Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/timers.adoc Shows timer creation when @MeterTag utilizes a ValueResolver to extract tag values from a parameter. ```java include::../../../samples/src/test/java/io/micrometer/docs/metrics/TimedAspectTest.java[tags=example_value_resolver,indent=0] ``` -------------------------------- ### Custom TracingObservationHandler Example Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-testing.adoc Example of a custom TracingObservationHandler, useful for unit testing custom tracing logic. ```java public class TracingTestingTests { @Test void observationHandler() { var observation = Observation.start("test", OBSERVATION_REGISTRY).orElseThrow(); observation.event(Event.of("test")); observation.stop(); } private static final ObservationRegistry OBSERVATION_REGISTRY = new ObservationRegistry.Builder() .observationConfig(config -> config.observationHandler(new TracingObservationHandler<>(new SimpleTracer()))) .build(); } ``` -------------------------------- ### Configure SignalFx via Properties Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/signalFx.adoc This example demonstrates configuring SignalFx using application properties, typically in a Spring Boot environment. It shows how to set the access token and reporting interval using YAML. ```yml management.metrics.export.signalfx: access-token: MYTOKEN # The interval at which metrics are sent to Ganglia. See Duration.parse for the expected format. # The default is 1 minute. step: 1m ``` -------------------------------- ### Integration Test with SampleTestRunner Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-testing.adoc Example of running integration tests using SampleTestRunner to assert spans against running Wavefront or Zipkin instances. ```java @Test void observabilitySmokeTest() { var observation = Observation.start("test", OBSERVATION_REGISTRY).orElseThrow(); observation.event(Event.of("test")); observation.stop(); assertThat(SAMPLE_TEST_RUNNER.getSpans()).hasSize(1); assertThat(SAMPLE_TEST_RUNNER.getSpans().get(0).getEvents()).hasSize(1); } private static final SampleTestRunner SAMPLE_TEST_RUNNER = new SampleTestRunner(new BraveTracer()); private static final ObservationRegistry OBSERVATION_REGISTRY = new ObservationRegistry.Builder() .observationConfig(config -> config.observationHandler(new TracingObservationHandler<>(SAMPLE_TEST_RUNNER))) .build(); ``` -------------------------------- ### Baggage Setup for Brave Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-api.adoc Important setup note for Brave: ensure the `PropagationFactory` is configured to include the baggage fields used in your code. This is essential for correct baggage propagation. ```java final PropagationFactory propagationFactory = new BravePropagationFactory.Builder() .add(BaggageField.newString("baggage key")) .build(); final Tracing tracing = Tracing.newBuilder() .propagationFactory(propagationFactory) .build(); final Tracer tracer = BraveTracer.builder(tracing).build(); ``` -------------------------------- ### Example Timer Creation with @MeterTag (SpEL) Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/timers.adoc Illustrates timer creation when @MeterTag uses a ValueExpressionResolver (SpEL) to determine tag values from a parameter. ```java include::../../../samples/src/test/java/io/micrometer/docs/metrics/TimedAspectTest.java[tags=example_value_spel,indent=0] ``` -------------------------------- ### Configure Micrometer CloudWatch via Properties Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/cloudwatch.adoc This example demonstrates configuring Micrometer CloudWatch export using YAML properties. It shows how to set the namespace, enable publishing, and define the reporting interval (step). ```yml management.metrics.export.cloudwatch: namespace: YOURNAMESPACE # You will probably want to disable publishing in a local development profile. enabled: true # The interval at which metrics are sent to CloudWatch. The default is 1 minute. step: 1m ``` -------------------------------- ### Configure AppOptics Meter Registry Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/appOptics.adoc Provides a Java code example for creating an AppOpticsMeterRegistry with a custom AppOpticsConfig. Ensure MY_TOKEN is replaced with your actual API token. ```java AppOpticsConfig appopticsConfig = new AppOpticsConfig() { @Override public String apiToken() { return MY_TOKEN; } @Override @Nullable public String get(String k) { return null; } }; MeterRegistry registry = new AppOpticsMeterRegistry(appopticsConfig, Clock.SYSTEM); ``` -------------------------------- ### Basic Gauge Metrics Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/gauges.adoc Example of defining and reporting basic Gauge metrics in Prometheus exposition format. ```plaintext # HELP my_gauge_seconds # TYPE my_gauge_seconds gauge my_gauge_seconds 4.0 # HELP my_other_gauge_seconds # TYPE my_other_gauge_seconds gauge my_other_gauge_seconds 0.004 ``` -------------------------------- ### Expose Prometheus Metrics with simpleclient_httpserver Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/prometheus.adoc This example shows how to use `io.prometheus.client.exporter.HTTPServer` from the `simpleclient_httpserver` library to expose Prometheus metrics. It's a convenient way to set up a scrape endpoint. ```java PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); // you can set the daemon flag to false if you want the server to block new HTTPServer(new InetSocketAddress(8080), prometheusRegistry.getPrometheusRegistry(), true); ``` -------------------------------- ### Configure StackdriverMeterRegistry with StackdriverConfig Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/stackdriver.adoc Implement StackdriverConfig to provide project ID and build a StackdriverMeterRegistry. The get(String k) method can be overridden to bind to property sources for custom configuration. ```java StackdriverConfig stackdriverConfig = new StackdriverConfig() { @Override public String projectId() { return MY_PROJECT_ID; } @Override public String get(String key) { return null; } } MeterRegistry registry = StackdriverMeterRegistry.builder(stackdriverConfig).build(); ``` -------------------------------- ### Maven POM for Micrometer Docs Generator Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-docs-gen.adoc Example Maven pom.xml configuration for integrating the Micrometer Docs Generator project. ```xml include::../../../samples/src/test/resources/docs-generator-pom.xml[indent=0] ``` -------------------------------- ### Customizing Dynatrace API Version Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/dynatrace.adoc This example demonstrates how to explicitly set the Dynatrace API version to v2 while accepting default configurations for other properties. ```java DynatraceConfig dynatraceConfig = new DynatraceConfig() { @Override public DynatraceApiVersion apiVersion() { return DynatraceApiVersion.V2; } @Override @Nullable public String get(String k) { return null; // accept the rest of the defaults } }; MeterRegistry registry = new DynatraceMeterRegistry(dynatraceConfig, Clock.SYSTEM); ``` -------------------------------- ### Observation Convention Example with Default Tags Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-handler.adoc Define an ObservationConvention to provide sensible defaults for tags and allow users to override them. ```java public class MyConvention implements ObservationConvention { @Override public boolean supportsContext(Observation.Context context) { return context instanceof MyContext; } @Override public String name(Observation.Context context) { return "my-operation"; } @Override public String[] tags(Observation.Context context) { return new String[] {"custom", "tag"}; } @Override public void onStop(Observation.Context context) { ObservationConvention.super.onStop(context); } } ``` -------------------------------- ### Dynatrace v2 Exporter Configuration Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/dynatrace.adoc Example of configuring the Dynatrace v2 exporter with explicit URI and API token. Ensure the API token has 'Ingest metrics' permission. ```java DynatraceConfig dynatraceConfig = new DynatraceConfig() { @Override public DynatraceApiVersion apiVersion() { return DynatraceApiVersion.V2; } @Override public String uri() { // The endpoint of the Dynatrace Metrics API v2 including path, e.g.: // "https://{your-environment-id}.live.dynatrace.com/api/v2/metrics/ingest". String endpoint = System.getenv("ENVVAR_METRICS_INGEST_URL"); return endpoint != null ? endpoint : DynatraceConfig.super.uri(); } @Override public String apiToken() { // should be read from a secure source String token = System.getenv("ENVVAR_METRICS_INGEST_TOKEN"); return token != null ? token : ""; } @Override public String metricKeyPrefix() { // will be prepended to all metric keys return "your.desired.prefix"; } @Override public boolean enrichWithDynatraceMetadata() { return true; } @Override public Map defaultDimensions() { // create and return a map containing the desired key-value pairs. ``` -------------------------------- ### Instrumenting HTTP Client Communication Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-instrumenting.adoc This example demonstrates how to instrument HTTP client communication using `RequestReplySenderContext`. It shows a custom handler that adds a 'foo:bar' header to outgoing requests. ```java final ObservationRegistry observationRegistry = ObservationRegistry.create(); final HttpRequest request = HttpRequest.newBuilder().uri("http://localhost:8080").build(); final HttpResponse response = HttpResponse.newBuilder().build(); final RequestReplySenderContext context = new RequestReplySenderContext<>( (req, key, val) -> req.header(key, val), req -> req.method(), req -> req.uri().toString(), req -> req.header("foo"), resp -> resp.statusCode(), resp -> resp.header("foo"), request, response ); context.add("foo", "bar"); final Observation observation = Observation.createNotStarted("http-client", observationRegistry) .contextualize(ctx -> ctx.set(RequestReplySenderContext.KEY, context)); observation.start(); // Simulate sending the request and receiving a response observation.stop(); ``` -------------------------------- ### Store and Restore ThreadLocal Values Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/contextpropagation/context-usage.adoc Example demonstrating storing and restoring thread local values using ThreadLocalAccessor, ContextSnapshot, and ContextRegistry. ```java @Test void simple() { ContextRegistry contextRegistry = new ContextRegistry(); contextRegistry.registerThreadLocalAccessor(new ObservationThreadLocalAccessor()); // Store thread local value ObservationThreadLocalHolder.set("test-value"); // Capture context ContextSnapshot contextSnapshot = contextRegistry.captureSnapshot(); // Remove thread local value ObservationThreadLocalHolder.remove(); assertNull(ObservationThreadLocalHolder.get()); // Restore context contextSnapshot.restore(); assertEquals("test-value", ObservationThreadLocalHolder.get()); } ``` -------------------------------- ### Span Example: No Custom Span Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-glossary.adoc Demonstrates a span with a trace ID and span ID, without a custom span indication. ```text Trace Id = X Span Id = A (no custom span) ``` -------------------------------- ### Configure Registry with Meter Filters Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/meter-filters.adoc Add meter filters to a registry configuration to ignore specific tags or deny meters starting with a given prefix. ```java registry.config() .meterFilter(MeterFilter.ignoreTags("too.much.information")) .meterFilter(MeterFilter.denyNameStartsWith("jvm")); ``` -------------------------------- ### Scrape Metrics in OpenMetrics Format Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/prometheus.adoc This example shows how to retrieve metrics in the OpenMetrics 1.0.0 format by passing the appropriate content type to the `scrape` method of the `PrometheusMeterRegistry`. This is useful for compatibility with systems that prefer the OpenMetrics standard. ```java String openMetricsScrape = registry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100); ``` -------------------------------- ### Query Long Task Timer Metrics Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/atlas.adoc This example demonstrates how to query for long task timer metrics, specifically focusing on the duration of long tasks. It includes parameters for filtering, visualization, and legend display. ```http GET /api/v1/graph?\ q=\ name,longTaskTimer,:eq,statistic,duration,:eq,:and, <1> \ :dup, 70,:gt,:vspan,f00,:color,40,:alpha,alerted,:legend, <2> \ 70,f00,:color,alert+threshold,:legend <3> \ &tz=US/Central &s=e-15m &w=400 &l=0 &title=Peaks+of+Long+Tasks &ylabel=time Host: localhost:7101 ``` -------------------------------- ### Configure New Relic Meter Registry Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/new-relic.adoc Example of configuring the NewRelicConfig interface to set account ID and API key for the NewRelicMeterRegistry. Uses default settings for other properties. ```java NewRelicConfig newRelicConfig = new NewRelicConfig() { @Override public String accountId() { return "MYACCOUNT"; } @Override public String apiKey() { return "MY_INSIGHTS_API_KEY"; } @Override public String get(String k) { return null; // accept the rest of the defaults } }; MeterRegistry registry = new NewRelicMeterRegistry(newRelicConfig, Clock.SYSTEM); ``` -------------------------------- ### Configure Distribution Statistics with MeterFilter Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/meter-filters.adoc Create a custom MeterFilter to configure distribution statistics for meters matching a specific name prefix. This example sets publish percentiles for matching meters. ```java new MeterFilter() { @Override public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) { if (id.getName().startsWith(prefix)) { return DistributionStatisticConfig.builder() .publishPercentiles(0.9, 0.95) .build() .merge(config); } return config; } } ``` -------------------------------- ### AppOptics Configuration Properties Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/appOptics.adoc Example YAML configuration for AppOptics export, including API token, enablement, and publishing interval. This is useful for Spring Boot applications. ```yml management.metrics.export.appoptics: api-token: YOURKEY # You will probably want disable AppOptics publishing in a local development profile. enabled: true # The interval at which metrics are sent to AppOptics. The default is 1 minute. step: 1m ``` -------------------------------- ### Customize StatsD Line Sink with a Logger Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/statsD.adoc This example demonstrates how to customize the StatsdMeterRegistry by providing a custom line sink, which in this case logs each metric line using a logger. ```java Consumer lineLogger = line -> logger.info(line); MeterRegistry registry = StatsdMeterRegistry.builder(StatsdConfig.DEFAULT) .clock(clock) .lineSink(lineLogger) .build(); ``` -------------------------------- ### Create a Basic Distribution Summary Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/distribution-summaries.adoc This snippet shows the simplest way to create a distribution summary, registering it with the provided registry. ```java DistributionSummary summary = registry.summary("response.size"); ``` -------------------------------- ### Elasticsearch Export Configuration Properties Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/elastic.adoc Example YAML configuration for Micrometer's Elasticsearch export. This allows enabling publishing, setting the reporting interval (step), and specifying the index name. ```yml management.metrics.export.elastic: # You will probably want disable Elastic publishing in a local development profile. enabled: true # The interval at which metrics are sent to Elastic. The default is 1 minute. step: 1m # The index to store metrics in, defaults to "micrometer-metrics" index: micrometer-metrics ``` -------------------------------- ### Humio Export Configuration via Properties Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/humio.adoc Example of configuring Humio export using application properties, commonly used in Spring Boot applications. This allows for externalizing sensitive information like API tokens. ```yml management.metrics.export.humio: api-token: YOURKEY # You will probably want disable Humio publishing in a local development profile. enabled: true # The interval at which metrics are sent to Humio. The default is 1 minute. step: 1m # The cluster Micrometer will send metrics to. The default is "https://cloud.humio.com" uri: https://myhumiohost ``` -------------------------------- ### Enabling Automated Context Propagation in Reactor Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-instrumenting.adoc This example shows how to enable automated context propagation for Reactor 3.5.3 and later by calling a Reactor Hook method. This ensures context is propagated between operators and threads without manual intervention. ```java public static void main(String[] args) { // ... other setup Hooks.enableAutomaticContextPropagation(); // ... rest of your application } ``` -------------------------------- ### Create Service Account and Key for Stackdriver Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/stackdriver.adoc Set up Google Cloud credentials by creating a service account, granting it Stackdriver Monitoring permissions, and generating a JSON key file. This key file should be referenced by the GOOGLE_APPLICATION_CREDENTIALS environment variable. ```bash export PROJECT_ID=MY_PROJECT_ID export APP_NAME=MY_APP # Create a service account gcloud iam service-accounts create $APP_NAME # Grant the service account Stackdriver Monitoring writer permission gcloud projects add-iam-policy-binding $PROJECT_ID \ --member serviceAccount:$APP_NAME@$PROJECT_ID.iam.gserviceaccount.com \ --role roles/monitoring.metricWriter # Create a key JSON file gcloud iam service-accounts keys create $HOME/$APP_NAME-key.json \ --iam-account $APP_NAME@$PROJECT_ID.iam.gserviceaccount.com ``` -------------------------------- ### Create a Distribution Summary with Builder Options Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/distribution-summaries.adoc Utilizes the fluent builder pattern to configure a distribution summary with optional descriptions, base units, tags, and a scaling factor. ```java DistributionSummary summary = DistributionSummary .builder("response.size") .description("a description of what this summary does") // optional .baseUnit("bytes") // optional <1> .tags("region", "test") // optional .scale(100) // optional <2> .register(registry); ``` -------------------------------- ### Deploy Site to GitHub Pages Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/README.md Command to deploy the site to GitHub Pages. ```bash ./gradlew publish (or yarn deploy) ``` -------------------------------- ### Observed Service Method Annotation Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-handler.adoc Example of an `ObservedService` with the `@Observed` annotation on a method. This allows for method-level observation. ```java package io.micrometer.docs.observation; import io.micrometer.observation.annotation.Observed; import org.springframework.stereotype.Service; @Service public class ObservedService { @Observed(name = "observedService.method") public String observedMethod() { return "observedMethod"; } public String notObservedMethod() { return "notObservedMethod"; } } ``` -------------------------------- ### Span Example: Custom Span Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-glossary.adoc Shows a span with a trace ID and span ID, indicating a custom span. ```text Trace Id = X Span Id = C (custom span) ``` -------------------------------- ### Create and Register MultiGauge Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/gauges.adoc Demonstrates how to build and register a MultiGauge to track metrics for a dynamic set of criteria, such as rows from a database query. ```java // SELECT count(*) from job group by status WHERE job = 'dirty' MultiGauge statuses = MultiGauge.builder("statuses") .tag("job", "dirty") .description("The number of widgets in various statuses") .baseUnit("widgets") .register(registry); ... // run this periodically whenever you re-run your query statuses.register( resultSet.stream() .map(result -> Row.of(Tags.of("status", result.getAsString("status")), result.getAsInt("count"))) .collect(toList()) ); ``` -------------------------------- ### Configure Micrometer Azure Monitor in Java Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/azure-monitor.adoc Instantiates an AzureMonitorConfig and MeterRegistry for sending metrics to Azure Monitor. Requires an instrumentation key. ```java AzureMonitorConfig azureMonitorConfig = new AzureMonitorConfig() { @Override public String instrumentationKey() { return MY_KEY; } @Override public String get(String key) { return null; } }; MeterRegistry registry = new AzureMonitorMeterRegistry(azureMonitorConfig, Clock.SYSTEM); ``` -------------------------------- ### Span Example: Client Sent Event Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-glossary.adoc Illustrates a span with a trace ID, span ID, and a 'Client Sent' event. ```text Trace Id = X Span Id = D Client Sent ``` -------------------------------- ### Run Development Mode Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/README.md Use this command to check changes to the repository locally in development mode. ```bash ./gradlew yarnStart (or yarn start) ``` -------------------------------- ### GET /api/v1/graph Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/atlas.adoc Retrieves a graph visualization of metrics data. Supports filtering, alerting thresholds, and custom display options. ```APIDOC ## GET /api/v1/graph ### Description Retrieves a graph visualization of metrics data. This endpoint allows for complex queries to filter and display metrics, including the ability to set alerts based on thresholds and customize the graph's appearance. ### Method GET ### Endpoint /api/v1/graph ### Parameters #### Query Parameters - **q** (string) - Required - The query string to filter and shape the metrics data. It supports a DSL for defining metrics, conditions, and visual elements. - Example: `name,longTaskTimer,:eq,statistic,duration,:eq,:and,:dup,70,:gt,:vspan,f00,:color,40,:alpha,alerted,:legend,70,f00,:color,alert+threshold,:legend` - **tz** (string) - Optional - The timezone to use for interpreting time-based data. Example: `US/Central` - **s** (string) - Optional - The time range or step for the graph. Example: `e-15m` - **w** (integer) - Optional - The width of the graph in pixels. Example: `400` - **l** (integer) - Optional - The number of lines to display. Example: `0` - **title** (string) - Optional - The title of the graph. Example: `Peaks+of+Long+Tasks` - **ylabel** (string) - Optional - The label for the Y-axis. Example: `time` ### Request Example ```http GET /api/v1/graph?q=name,longTaskTimer,:eq,statistic,duration,:eq,:and,:dup,70,:gt,:vspan,f00,:color,40,:alpha,alerted,:legend,70,f00,:color,alert+threshold,:legend&tz=US/Central&s=e-15m&w=400&l=0&title=Peaks+of+Long+Tasks&ylabel=time Host: localhost:7101 ``` ### Response #### Success Response (200) - The response will be an image or data representing the graph, depending on the `Accept` header and query parameters. Specific fields are not detailed in the source but would typically include graph data or image bytes. #### Response Example (Response content is typically an image or structured data representing the graph, not explicitly defined in the source.) ``` -------------------------------- ### Direct Netty Instrumentation Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/netty/index.adoc Instrument Netty resources directly at startup when they are known. This approach is suitable for initial configuration. ```java ByteBufAllocator allocator = ByteBufAllocator.DEFAULT; EventLoopGroup group = new NioEventLoopGroup(); Micrometer.configure(allocator, group); ``` -------------------------------- ### HTTP Client Handler Instrumentation Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-instrumenting.adoc Instruments HTTP client requests by reusing a handler. This snippet demonstrates the setup for client-side observation. ```java var httpClientHandler = new HttpClientHandler() { @Override protected void onStart(HttpClientRequest request) { request.withHeader("traceparent", "00-0af7651916cd43dd844823725f83644d-0000000000000001-01"); } @Override protected void onSuccess(HttpClientRequest request) { } @Override protected void onError(HttpClientRequest request, Throwable throwable) { } @Override protected void onCancel(HttpClientRequest request) { } @Override protected void onStop(HttpClientRequest request) { } }; var observation = Observation.builder("http-client", httpClientHandler) .contextualName("GET /api/greeting") .lowCardinalityKey("http.method", "GET") .highCardinalityKey("http.url", "http://localhost:8080/api/greeting") .observe(() -> { // Simulate HTTP client call System.out.println("Making HTTP client call..."); return "response"; }); observation.start().stop(); ``` -------------------------------- ### Add OkHttpMetricsEventListener to OkHttpClient Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/okhttpclient/index.adoc Collect metrics from OkHttpClient by adding OkHttpMetricsEventListener. This basic setup uses a default registry and metric name. ```java OkHttpClient client = new OkHttpClient.Builder() .eventListener(OkHttpMetricsEventListener.builder(registry, "okhttp.requests") .tags(Tags.of("foo", "bar")) .build()) .build(); ``` -------------------------------- ### Implement a Simple Observation Handler Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/observation/observation-handler.adoc Create a basic ObservationHandler that prints invocation details to stdout for demonstration purposes. ```java public class SimpleHandler implements ObservationHandler { @Override public void onStart(Observation.Context context) { System.out.println("Starting observation: " + context.getName()); } @Override public void onStop(Observation.Context context) { System.out.println("Stopping observation: " + context.getName()); } @Override public void onError(Observation.Context context) { System.out.println("Observation error: " + context.getName()); } @Override public boolean supportsContext(Observation.Context context) { return true; } } ``` -------------------------------- ### Automatic Timing with @Timed Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/timers.adoc The @Timed annotation automatically records the execution time of a method. It measures from the start until the returned CompletableFuture completes. ```java public CompletableFuture async() { // @Timed will record the execution time of this method, // from the start and until the returned CompletableFuture // completes normally or exceptionally. return CompletableFuture.supplyAsync(...); } } ``` -------------------------------- ### Configure StatsD Meter Registry with Etsy Flavor Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/statsD.adoc This snippet shows how to create a StatsdMeterRegistry with a custom StatsdConfig that explicitly uses the Etsy flavor. Metrics are sent immediately over UDP. ```java StatsdConfig config = new StatsdConfig() { @Override public String get(String k) { return null; } @Override public StatsdFlavor flavor() { return StatsdFlavor.Etsy; } }; MeterRegistry registry = new StatsdMeterRegistry(config, Clock.SYSTEM); ``` -------------------------------- ### Prometheus Query for Counter Rate Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/prometheus.adoc Example Prometheus query to calculate the rate of a counter over a 10-second window, representing requests per second. ```promql rate(counter[10s]) ``` -------------------------------- ### Observe Object, Collection Size, and Map Size with Gauges Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/gauges.adoc Demonstrates creating gauges to observe the size of a List, a collection, and a map. The last argument for the object gauge is a function to determine its value. ```java List list = registry.gauge("listGauge", Collections.emptyList(), new ArrayList<>(), List::size); <1> List list2 = registry.gaugeCollectionSize("listSize2", Tags.empty(), new ArrayList<>()); <2> Map map = registry.gaugeMapSize("mapGauge", Tags.empty(), new HashMap<>()); ``` -------------------------------- ### Configure Direct Wavefront Sending Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/wavefront.adoc Configures sending metrics directly to the Wavefront API. Requires a Wavefront API token and the Wavefront instance URI. ```java WavefrontConfig config = new WavefrontConfig() { @Override public String uri() { return "https://longboard.wavefront.com"; } @Override public String apiToken() { return "MYAPIKEY"; } @Override public String get(String key) { return null; } }; MeterRegistry registry = new WavefrontMeterRegistry(config, Clock.SYSTEM); ``` -------------------------------- ### Define Custom Meter Registry Configuration Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/guide/custom-meter-registry.adoc Extend `StepRegistryConfig` to define configuration properties for your custom meter registry. This example sets a default prefix for metrics. ```java public interface CustomRegistryConfig extends StepRegistryConfig { CustomRegistryConfig DEFAULT = k -> null; @Override default String prefix() { return "custom"; } } ``` -------------------------------- ### Verifying Spans with SimpleTracer Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-testing.adoc Demonstrates how to use SimpleTracer to verify that spans were created correctly in unit tests. ```java @Test void handlerTest() { var observation = Observation.start("test", OBSERVATION_REGISTRY).orElseThrow(); observation.event(Event.of("test")); observation.stop(); assertThat(SIMPLE_TRACER.getSpans()).hasSize(1); assertThat(SIMPLE_TRACER.getSpans().get(0).getEvents()).hasSize(1); } private static final SimpleTracer SIMPLE_TRACER = new SimpleTracer(); private static final ObservationRegistry OBSERVATION_REGISTRY = new ObservationRegistry.Builder() .observationConfig(config -> config.observationHandler(new TracingObservationHandler<>(SIMPLE_TRACER))) .build(); ``` -------------------------------- ### Add Micrometer Gradle Implementation Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/install.adoc Use this snippet to add the Micrometer registry implementation to your Gradle project. Replace '{system}' with your target system. ```groovy implementation 'io.micrometer:micrometer-registry-{system}:latest.release' ``` -------------------------------- ### Configure Datadog Meter Registry Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/datadog.adoc Instantiate a DatadogMeterRegistry with custom configuration, setting the step interval and accepting default properties. ```java DatadogConfig config = new DatadogConfig() { @Override public Duration step() { return Duration.ofSeconds(10); } @Override public String get(String k) { return null; // accept the rest of the defaults } }; MeterRegistry registry = new DatadogMeterRegistry(config, Clock.SYSTEM); ``` -------------------------------- ### Registering a TimeGauge Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/gauges.adoc Register a TimeGauge with a specific name, a function to get the time value, the time unit, and a function to extract the numeric value. This is useful for measuring durations. ```java TimeGauge.builder("my.gauge", msTimeGauge, TimeUnit.MILLISECONDS, AtomicInteger::get).register(registry); TimeGauge.builder("my.other.gauge", usTimeGauge, TimeUnit.MICROSECONDS, AtomicInteger::get).register(registry); ``` -------------------------------- ### Fluent Counter Builder Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/counters.adoc Shows how to use the fluent builder for advanced counter configuration, including base units, descriptions, and tags, before registering the counter with the registry. ```java Counter counter = Counter .builder("counter") .baseUnit("beans") // optional .description("a description of what this counter does") // optional .tags("region", "test") // optional .register(registry); ``` -------------------------------- ### Manually Update Gauge with Settable Number Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/gauges.adoc Shows how to create a gauge that observes a settable number type like AtomicInteger. You get a reference to the number itself, which you can update directly. ```java // maintain a reference to myGauge AtomicInteger myGauge = registry.gauge("numberGauge", new AtomicInteger(0)); // ... elsewhere you can update the value it holds using the object reference myGauge.set(27); myGauge.set(11); ``` -------------------------------- ### Spring AOP Configuration for Span Aspects Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-api.adoc Example Spring AOP configuration for using Micrometer Tracing annotations like @NewSpan and @ContinueSpan. This enables aspect-oriented weaving for spans. ```java @Configuration @EnableMicrometerTracing @EnableAspectJAutoProxy public class TracingConfiguration { @Bean public SpanAspect spanAspect(final Tracer tracer) { return new SpanAspect(tracer); } } ``` -------------------------------- ### Configure Timer with Percentile Histogram Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/histogram-quantiles.adoc Builds a timer and configures it to publish percentile values and a histogram. This is useful for systems like Prometheus that support aggregable percentile approximations from histograms. ```java Timer.builder("my.timer") .publishPercentiles(0.5, 0.95) // median and 95th percentile <1> .publishPercentileHistogram() // <2> .serviceLevelObjectives(Duration.ofMillis(100)) // <3> .minimumExpectedValue(Duration.ofMillis(1)) // <4> .maximumExpectedValue(Duration.ofSeconds(10)) ``` -------------------------------- ### Atlas Export Configuration Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/atlas.adoc Example of how to configure Atlas export properties in a Spring Boot application. This allows overriding default settings like the server URI and publishing interval. ```yml management.metrics.export.atlas: # The location of your Atlas server uri: http://localhost:7101/api/v1/publish # You will probably want to conditionally disable Atlas publishing in local development. enabled: true # The interval at which metrics are sent to Atlas. The default is 1 minute. step: 1m ``` -------------------------------- ### Create Meters with the Global Registry Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/registry.adoc Utilize the static global registry `Metrics.globalRegistry` to create meters. It's recommended to store Meter instances in fields for performance-critical instrumentation. Tags determined from local context can be constructed or looked up within methods. ```java class MyComponent { Counter featureCounter = Metrics.counter("feature", "region", "test"); void feature() { featureCounter.increment(); } void feature2(String type) { Metrics.counter("feature.2", "type", type).increment(); } } class MyApplication { void start() { // wire your monitoring system to global static state Metrics.addRegistry(new SimpleMeterRegistry()); } } ``` -------------------------------- ### Continue Span in New Thread Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-api.adoc Shows how to continue a span in a new thread when it was initially started in another thread. This is crucial for maintaining trace context across asynchronous operations. ```java final Span span = tracer.nextSpan().name("parent span"); span.start(); executorService.submit(() -> { final Span childSpan = tracer.nextSpan(span); try { // do work } catch (Exception e) { childSpan.error(e); throw e; } finally { childSpan.end(); } }); span.end(); ``` -------------------------------- ### TimeGauge Registration with TimeUnit Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/gauges.adoc Demonstrates registering a TimeGauge with AtomicInteger instances, specifying the time unit for each. ```java AtomicInteger msTimeGauge = new AtomicInteger(4000); AtomicInteger usTimeGauge = new AtomicInteger(4000); ``` -------------------------------- ### Export Micrometer Metrics with Dynatrace Auto-Configuration Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/dynatrace.adoc Use this code when a Dynatrace OneAgent or Kubernetes operator is installed. It allows metrics to be exported directly without explicit endpoint or token configuration. ```java DynatraceConfig dynatraceConfig = new DynatraceConfig() { @Override @Nullable public String get(String k) { // This method of the interface is used by the other configuration methods and needs to be // implemented here. Returning null accepts the defaults for the other configuration items. return null; } }; MeterRegistry registry = new DynatraceMeterRegistry(dynatraceConfig, Clock.SYSTEM); ``` -------------------------------- ### Applying @NewSpan and @ContinueSpan with AspectJ Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/tracing/tracing-api.adoc Demonstrates how to apply @NewSpan and @ContinueSpan annotations on methods within an AspectJ proxied instance. This allows for automatic span creation and continuation. ```java @Service public class MyService { @NewSpan public void methodWithNewSpan() { // ... } @ContinueSpan("existingSpanName") public void methodWithContinueSpan() { // ... } } ``` -------------------------------- ### Gauge Fluent Builder Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/concepts/gauges.adoc Illustrates using the fluent builder pattern to create and configure a gauge. This is generally useful for testing as the gauge is automatically registered. ```java Gauge gauge = Gauge .builder("gauge", myObj, myObj::gaugeValue) .description("a description of what this gauge does") // optional .tags("region", "test") // optional .register(registry); ``` -------------------------------- ### Configure and Initialize StatsD Meter Registry Source: https://github.com/micrometer-metrics/micrometer-docs/blob/main/src/docs/implementations/influx.adoc Configure the StatsD registry to use Telegraf's flavor of the StatsD line protocol and initialize the MeterRegistry. Metrics are sent immediately over UDP. ```java StatsdConfig config = new StatsdConfig() { @Override public String get(String k) { return null; } @Override public StatsdFlavor flavor() { return StatsdFlavor.Telegraf; } }; MeterRegistry registry = new StatsdMeterRegistry(config, Clock.SYSTEM); ```