.NET 8 Windows Forms应用基于OpenTelemetry对接Prometheus指标采集问询
.NET Windows Forms 配置 OpenTelemetry + Prometheus Exporter 采集指标
1. 安装必要的NuGet包
通过NuGet包管理器或CLI安装以下包:
OpenTelemetryOpenTelemetry.Exporter.Prometheus.HttpListenerOpenTelemetry.Instrumentation.Http(用于自动采集HTTP调用指标)OpenTelemetry.Extensions.Hosting(用于管理OpenTelemetry生命周期)
2. 初始化OpenTelemetry与Prometheus Exporter
在WinForms应用的入口(Program.cs的Main方法)中完成初始化,这里需要启动一个HTTP监听器供Prometheus抓取指标:
using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Exporter.Prometheus.HttpListener; using System.Windows.Forms; namespace WinFormsOtelPrometheus { internal static class Program { [STAThread] static void Main() { // 构建MeterProvider并启动Prometheus HTTP监听器 using var meterProvider = Sdk.CreateMeterProviderBuilder() // 注册自定义Meter(如果需要自定义指标) .AddMeter("WinFormsApp.CustomMetrics") // 自动采集HttpClient调用的指标 .AddHttpClientInstrumentation() // 配置Prometheus Exporter .AddPrometheusHttpListener(options => { // 设置监听地址,确保端口未被占用 options.UriPrefixes = new[] { "http://localhost:9184/" }; // Prometheus抓取的端点路径 options.ScrapeEndpointPath = "/metrics"; }) .Build(); // 启动WinForms应用 ApplicationConfiguration.Initialize(); Application.Run(new MainForm()); } } }
3. 添加自定义指标(可选)
如果需要采集业务自定义指标,比如API调用次数,可以在Form中定义Meter和计数器:
using System.Diagnostics.Metrics; using System.Net.Http; using System.Windows.Forms; namespace WinFormsOtelPrometheus { public partial class MainForm : Form { // 定义自定义Meter和计数器 private static readonly Meter _customMeter = new Meter("WinFormsApp.CustomMetrics", "1.0.0"); private readonly Counter<int> _apiCallCounter = _customMeter.CreateCounter<int>( name: "api_calls_total", description: "Total number of API calls initiated by the app"); public MainForm() { InitializeComponent(); } private async void btnInvokeApi_Click(object sender, EventArgs e) { using var httpClient = new HttpClient(); try { var response = await httpClient.GetAsync("http://localhost:8080/api"); response.EnsureSuccessStatusCode(); // 记录成功的API调用 _apiCallCounter.Add(1, new KeyValuePair<string, object>("status", "success")); } catch (Exception ex) { // 记录失败的API调用,附带错误信息 _apiCallCounter.Add(1, new KeyValuePair<string, object>("status", "failure"), new KeyValuePair<string, object>("error", ex.Message)); } } } }
4. 配置Prometheus抓取
在Prometheus的配置文件(prometheus.yml)中添加以下抓取任务:
scrape_configs: - job_name: 'winforms_app' scrape_interval: 15s static_configs: - targets: ['localhost:9184']
关键注意事项
- 确保WinForms应用有足够权限监听指定端口(若使用1024以下端口,需以管理员身份运行)
- 启动应用后,可直接访问
http://localhost:9184/metrics验证指标是否正常输出 - 若不需要自动采集HTTP调用指标,可移除
.AddHttpClientInstrumentation()配置 - 自定义Meter的名称需唯一,避免与其他组件的Meter冲突
内容的提问来源于stack exchange,提问作者Rohan
相关产品推荐
相关产品推荐

