DEV Community

Cover image for net6 API Prometheus Metrics
Dylan Morley
Dylan Morley

Posted on

net6 API Prometheus Metrics

If you're creating a dotnet API to run in Kubernetes, chances are you'll be wanting to use Prometheus to gather metrics about your application.

A library that makes this really easy for us is prometheus-net - we can create a minimal API that exposes metrics quickly and demonstrate a few different ways of creating metric data

The source for this is in github at https://github.com/dylanmorley/dotnet-api-prometheus-metrics-reference

Metrics Configuration

The majority of the work for this is done in the Program startup class, let's look at a few of the important points

EventCounterAdapter - listens for any dotnet event counters and converts them into Prometheus format at the exporter endpoint

MeterAdapter - listens for dotnet metrics created via System.Diagnostics.Metrics Meter

app.UseHttpMetrics - we want the application to expose metrics about each one of our endpoints, such as number of requests, request durations

app.UseEndpoints -> MapMetrics - we'll expose the /metrics endpoint as part of the application

That's pretty much it, not many things to configure and our app is up and running

Controller usage

In the weather forecast controller there are a couple of examples of how metrics can now be created.

If you execute the WeatherForecast/Get endpoint, you'll be incrementing a metric created by a System.Diagnostics.Metrics Meter instance, and if you hit WeatherForecast/PredictStorm you'll be using a Histogram from the prometheus-net library.

After executing either of these methods, you can check the /metrics endpoint and will see various event counters, custom counters & http controller endpoint metrics, all converted into Prometheus format and ready for scraping.

A docker file is included in the repo, to demonstrate creating an image that could then be run alongside a Prometheus instance on a kubernetes cluster.

That's it - a super simple reference solution for getting metrics up and running

Discussion (0)