Add new custom Prometheus metric in an Akka HTTP application

We have already discussed in my previous blog that how to expose the metrics in an Akka http application in prometheus format. In this blog we will discuss, how to add a new custom metric in the Akka http application.

We usually love to customise the things in our own way, similarily we can customise the metrics as per our requirement. Let see how we can achieve that.

Before going into the implementation, let’s understand the requirement first. I need the count of requests per user id. We get the path, status and method as default label in metrics but not the userId. So I decided to write a custom metrics having label as userId which will help me to meet my requirement.

First of all, we need to create a custom counter and then register it with the collector registry.

import com.rishi.metrics.controller.MetricsController.{collector, settings}
import fr.davit.akka.http.metrics.core.Dimension
import io.prometheus.client.Counter

object TotalRequestByUserIdMetric {
  private val userIdLabel: Seq[String] = Seq("userId")

  private val totalRequestCounter: Counter = Counter.build().
    namespace(settings.namespace)
    .name("request_by_user_id")
    .help("Total Request by User ID")
    .labelNames(userIdLabel: _*)
    .register(collector)

  def inc(dimensions: Seq[Dimension]): Unit = {
    totalRequestCounter.labels(dimensions.map(_.value): _*).inc()
  }
}

final case class UserIdDimension(userId: String) extends Dimension {
  override def key: String = "userId"

  override def value: String = userId
}

I have taken “userId” as label name and have added the corrosponding name and help accordingly.

Then, we need to call it from the desired place:

TotalRequestByUserIdMetric.inc(List(UserIdDimension(userId)))

Here, I am calling the inc() function with the userId to increment the counter.

That’s it. We are done. It’s pretty simple.

Let’s hit the below url and see the generated metrics:

http://localhost:8080/user?userId=3

You can get the full code here.

I hope this blog will help you in someway.

About Rishi Khandelwal

Rishi is a tech enthusiast with having around 10 years of experience who loves to solve complex problems with pure quality. He is a functional programmer and loves to learn new trending technologies. His leadership skill is well prooven and has delivered multiple distributed applications with high scalability and availability by keeping the Reactive principles in mind. He is well versed with Scala, Akka, Akka HTTP, Akka Streams, Java8, Reactive principles, Microservice architecture, Async programming, functional programming, distributed systems, AWS, docker.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment