Define custom MicroProfile Telemetry metrics

You can use the OpenTelemetry metrics API to define custom metrics in your application code. When you enable the MicroProfile Telemetry feature 2.0 or later, you can then collect and emit these metrics to customize the observability of your application.

For more information about collecting and emitting metrics with MicroProfile Telemetry, see Collect logs, metrics, and traces with OpenTelemetry.

Before you can use OpenTelemetry to define custom metrics metrics, you must make 3rd party APIs visible in your runtime environment by editing your runtime configuration. For more information, see Customize your application telemetry with the OpenTelemetry API.

The following example defines a custom counter metric:

class WithCounter {
    @Inject
    Meter meter;

    private LongCounter counter;

    @PostConstruct
    public void init() {
        counter = meter
                    .counterBuilder("new_subscriptions")
                    .setDescription("Number of new subscriptions")
                    .setUnit("1")
                    .build();
    }

    void subscribe(String plan) {
        counter.add(1,
            Attributes.of(AttributeKey.stringKey("plan"), plan));
    }
}

In this example, Meter is used to define an instrument, in this case a Counter. Application code then can record measurement values along with other attributes. Measurement aggregations are computed separately for each unique combination of attributes.

For a full list of available metrics, see Meter operations in the OpenTelemetry documentation.

For more information about OpenTelemetry metrics, see the OpenTelemetry metrics API documentation.