This article will share how to enrich native metrics in Keycloak with Micrometer and add yours.
Special thanks
Thanks to all contributors who built one of the most use Keycloak plugin : https://github.com/aerogear/keycloak-metrics-spi
TL/DR
We developed a new metrics plugin for Keycloak based on aerogear implementation that enrich Keycloak native metrics.
Available on Github : https://github.com/please-openit/keycloak-native-metrics
Introduction
Keycloak has now native metrics available through a feature flag at launch : --metrics-enabled=true
https://www.keycloak.org/server/configuration-metrics
It exposes a /metrics endpoint on port 9000 thanks to Management interface .
A community plugin adds custom metrics (logins, registration etc…) and also http statistics. This plugin is an event listener with a custom endpoint (RealmResource).
Now with openmetrics available in Keycloak, we see how we can add our own metrics to the native management interface and avoid multiplying metrics endpoints with a simpler plugin.
MeterRegistry
with
import io.micrometer.core.instrument.MeterRegistry;
private class MyClass {
// get a meter registry
private final MeterRegistry meterRegistry = Metrics.globalRegistry;
// push a new metric
public void recordGoogleLogin() {
meterRegistry.counter("keycloak_login_attempts", "master", "Google", "security-admin-console").increment();
}
}
A counter (in this use case) has multiple tags and after increment is directly accessible through /metrics endpoint.
We also have :
- timers
- summaries
- gauge
New metrics plugin
Thanks to all contributors on https://github.com/aerogear/keycloak-metrics-spi, we think it is time to rebuild it by using those native metrics and simplifying it a lot.
With exactly the same structure, instead of building a custom « PrometheusExporter » object, we push our own metrics to a MeterRegistry.
All events are caught from an « EventListener », so you have to register it in order to enable it.
We also removed all http metrics, Keycloak already provides them and also histograms : --http-metrics-histograms-enabled=true
https://github.com/please-openit/keycloak-native-metrics
TIP : caches metrics are also here ! Histograms enabled with : --cache-metrics-histograms-enabled=true
Go further
With this object « MeterRegistry » available everywhere in Keycloak, you are not limited now with custom events. You can easily monitor your own UserFederation or custom authenticator … every code you put in Keycloak has access to metrics, like you have logs.
- Keycloak roles restriction and full scopes - 10 décembre 2024
- How to enrich native metrics in KeyCloak - 21 août 2024
- Keycloak Authenticator explained - 7 mars 2024