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?
The following diagram illustrates the architecture of Prometheus and some of its ecosystem components.

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
- {
- // others ...
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- // others ...
- app.UseMetricServer();
- }
- }

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>();
- }
- }



Join the conversation! Your thoughts help the community grow.