简体   繁体   中英

How to integrate Prometheus with .NET Core application?

I am trying to integrate Prometheus for my C# .NET Core Console application. I am not developing an ASP.NET Core application . How do I send the metrics data to prometheus the way we usually do for ASP.NET Core application?

In ASP.NET Core application,

Open Startup.cs and update ConfigureServices and Configure to look something along the lines of:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<MetricReporter>();

    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Other middleware components omitted for brevity

    // Make sure these calls are made before the call to UseEndPoints.
    app.UseMetricServer();
    app.UseMiddleware<ResponseMetricMiddleware>();

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}

How can I do this for a .NET Core console application?

You can use the Prometheus-net package which provides some useful features for integrating .Net and Prometheus. Due to documentation you could start a kestrel-stand-alone server for console apps that do not have any accessible http endpoints. in order to that ,you must have the .Web at the end of the Sdk attribute value in the project file.

after that you need to start the kestrel:

var metricServer = new KestrelMetricServer(port: 1234);
metricServer.Start();

Another way is to simply use the standalone Http-handlers as follows:

var metricServer = new MetricServer(port: 1234);
metricServer.Start();

The default configuration will publish metrics on the /metrics URL.

MetricServer.Start() may throw an access denied exception on Windows if your user does not have the right to open a web server on the specified port. You can use the netsh command to grant yourself the required permissions:

netsh http add urlacl url=http://+:1234/metrics user=DOMAIN\user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM