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 Configuring Open Liberty to use MicroProfile Telemetry to collect metrics.

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

Before you can use MicroProfile Telemetry to define custom metrics metrics, you must enable MicroProfile Telemetry in your development environment by editing your runtime configuration. You must also add the OpenTelemetry API and annotations as a dependency on your build path. For more information, see Prepare your development environment for MicroProfile Telemetry.

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.