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
![](https://khandelwalrishi.wordpress.com/wp-content/uploads/2021/09/image.png?w=1024)
You can get the full code here.
I hope this blog will help you in someway.