Background
While our applications are running, we should have some monitoring of metrics for both system and business levels, so that we can easily measure the usage and performance, and diagnose any problems.
In this article, we will discuss how to monitor ASP.NET Core Apps using Prometheus.
What is Prometheus?
Prometheus is an open source monitoring platform. It provides multiple functionalities to store, manipulate, and monitor metrics from our applications.
The following diagram illustrates the architecture of Prometheus and some of its ecosystem components.
Metrics
For Prometheus metrics in ASP NET Core, we will be using
prometheus-net.
Let us start by installing it from NuGet.
- dotnet add package prometheus-net.AspNetCore
Next, we need to register it on the Application Builder.
- public class Startup
- {
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
-
-
- app.UseMetricServer();
- }
- }
When we run the application and navigate to
/metrics, we will get some default metrics set up by prometheus-net.
We can customize our own metrics based on the above illustration. For example, we want to be able to measure the requests for each endpoint, method and their status code (200 for succeed and 500 for error).
Here, we will use a middleware to record the metrics with counter, one of the metric types provide by Prometheus.
- public class RequestMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly ILogger _logger;
-
- public RequestMiddleware(
- RequestDelegate next
- , ILoggerFactory loggerFactory
- )
- {
- this._next = next;
- this._logger = loggerFactory.CreateLogger<RequestMiddleware>();
- }
-
- public async Task Invoke(HttpContext httpContext)
- {
- var path = httpContext.Request.Path.Value;
- var method = httpContext.Request.Method;
-
- var counter = Metrics.CreateCounter("prometheus_demo_request_total", "HTTP Requests Total", new CounterConfiguration
- {
- LabelNames = new[] { "path", "method", "status" }
- });
-
- var statusCode = 200;
-
- try
- {
- await _next.Invoke(httpContext);
- }
- catch (Exception)
- {
- statusCode = 500;
- counter.Labels(path, method, statusCode.ToString()).Inc();
-
- throw;
- }
-
- if (path != "/metrics")
- {
- statusCode = httpContext.Response.StatusCode;
- counter.Labels(path, method, statusCode.ToString()).Inc();
- }
- }
- }
-
- public static class RequestMiddlewareExtensions
- {
- public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder)
- {
- return builder.UseMiddleware<RequestMiddleware>();
- }
- }
Then, we should add this middleware on application builder so that we get our custom metrics.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
-
-
- app.UseMetricServer();
-
- app.UseRequestMiddleware();
- }
We also have to make some changes on the controller so, that we can record 500 status code.
- [HttpGet]
- public ActionResult<IEnumerable<string>> Get()
- {
- if(new System.Random().NextDouble() > 0.5)
- {
- throw new System.Exception("test exception");
- }
-
- return new string[] { "value1", "value2" };
- }
After re-running this application and visiting some endpoints, we will find out the metrics were recorded.
Setup And Run Prometheus
We will use docker to set up prometheus.
- FROM prom/prometheus
- ADD Prometheus/prometheus.yml /etc/prometheus/
prometheus.yml is the configuration file that configures how prometheus collects the metrics.
The following configuration specifies that prometheus will collect metrics via scraping.
- scrape_configs:
- - job_name: mydemo
- scrape_interval: 15s
- scrape_timeout: 10s
- metrics_path: /metrics
- scheme: http
- static_configs:
- - targets:
- - localhost:5000
Now, let's take a look at the metrics via Prometheus Web UI.
We also can combine Prometheus and Grafana to make a more pretty visualization.
And in this sample, we just used Counter, one of the metric types of Prometheus. There are three other main metric types available in prometheus.
The choice of selecting the type depends on your data and reporting needs. Just avoid forcing data into one type, without investigating if another type is a better fit.
Summary
This short article showed how to use Prometheus-net to create counters and save custom mertrics from our ASP.NET Core application.
I hope this article can help you!