# Prometheus JVM metrics

**URL:** <https://softwaremill.community/t/prometheus-jvm-metrics/429>\
**Category:** tapir\
**Created:** [August 7, 2024, 3:16pm UTC](https://softwaremill.community/t/prometheus-jvm-metrics/429 "2024-08-07T15:16:21Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![matejcerny](https://dub1.discourse-cdn.com/flex005/user_avatar/softwaremill.community/matejcerny/32/287_2.png) [@matejcerny](https://softwaremill.community/u/matejcerny)\
**Post date:** [August 7, 2024, 3:16pm UTC](https://softwaremill.community/t/prometheus-jvm-metrics/429/1 "2024-08-07T15:16:21Z")

</div>

Hi,

Any ideas on how to implement JVM metrics with tapir? So far, I’ve come up with this

```scala
object MetricsRouter:
  private val registry = PrometheusRegistry.defaultRegistry

  private val threadDemonCount = Metric[IO, Gauge](
    metric = Gauge.builder().name("jvm_threads_daemon_count").help("...").register(registry),
    onRequest = { (_, gauge, m) =>
      m.unit(
        EndpointMetric().onResponseBody((_, _) => IO(gauge.set(ManagementFactory.getThreadMXBean.getDaemonThreadCount)))
      )
    }
  )

  val Metrics: PrometheusMetrics[IO] =
    PrometheusMetrics
      .default[IO]()
      .addCustom(threadDemonCount)

```

Many thanks!

---

<div class="post-metadata">

**Author:** ![adamw](https://dub1.discourse-cdn.com/flex005/user_avatar/softwaremill.community/adamw/32/28_2.png) [@adamw](https://softwaremill.community/u/adamw)\
**Post date:** [August 7, 2024, 3:29pm UTC](https://softwaremill.community/t/prometheus-jvm-metrics/429/2 "2024-08-07T15:29:07Z")

</div>

I think you’d simply need to do `io.prometheus.client.hotspot.DefaultExports.initialize()`?

---

<div class="post-metadata">

**Author:** ![matejcerny](https://dub1.discourse-cdn.com/flex005/user_avatar/softwaremill.community/matejcerny/32/287_2.png) [@matejcerny](https://softwaremill.community/u/matejcerny)\
**Post date:** [August 8, 2024, 8:19am UTC](https://softwaremill.community/t/prometheus-jvm-metrics/429/3 "2024-08-08T08:19:53Z")

</div>

I tried it, but sadly no. This solution works, however I am not sure if it is not suboptimal as I don’t really understand how it works 😄 When is the `onResponseBody` called?

---

<div class="post-metadata">

**Author:** ![adamw](https://dub1.discourse-cdn.com/flex005/user_avatar/softwaremill.community/adamw/32/28_2.png) [@adamw](https://softwaremill.community/u/adamw)\
**Post date:** [September 3, 2024, 1:28pm UTC](https://softwaremill.community/t/prometheus-jvm-metrics/429/4 "2024-09-03T13:28:22Z")

</div>

> [@matejcerny](#):
>
> When is the `onResponseBody` called?

When the response’s body is completely sent
