• $ cat "

    Adding a Prometheus Metrics Endpoint to an ASP.NET MVC Application

    "

    The Prometheus-net nuget package contains a simple web server for hosting a metrics endpoint in process, but for an ASP.NET application it makes more sense just to add a metrics enpoint to the application.

    To add such an endpoint to an ASP.NET MVC application you simply add a MetricsController, that looks like this:

    public class MetricsController : Controller
    {
        public ActionResult Index()
        {
            var acceptHeader = Request.Headers.Get("Accept");
            var acceptHeaders = acceptHeader?.Split(',');
    
            Response.ContentType = ScrapeHandler.GetContentType(acceptHeaders);
    
            ScrapeHandler.ProcessScrapeRequest(
                DefaultCollectorRegistry.Instance.CollectAll(), 
                Response.ContentType, 
                Response.OutputStream);
    
            HttpContext.ApplicationInstance.CompleteRequest();
    
            // Irrelevant, since it is after the CompleteRequest call
            return null;
        } 
    }
    

    You can now go to the /metrics endpoint of your site and see all collected metrics. Remember that the page will be empty unless you actually do define some metrics (counters, guages etc). Check out the prometheus-net github page for details on how to do that.

    Note that Prometheus expects to be configured with a hostname (and port). It does not seem to like something like 192.160.0.1/foobar, but instead wants something like 192.168.0.1:12345. So, if you are working on your local machine, make sure to set up a proper IIS site with a binding to a custom port, rather than using IIS Express or hosting the site under the default IIS website.