CZGL.SystemInfo
一个.NET Core监控系统CPU内存等信息的工具
Install / Use
/learn @whuanle/CZGL.SystemInfoREADME
由于 .NET 7 之后,官方也做了 Prometheus、Metrics 收集,因此建议使用官方的库来实现:
https://learn.microsoft.com/zh-cn/dotnet/core/diagnostics/metrics-collection
由于官方都有相应功能了,因此这个库后面应该不会更新接入 Promethues 了。
这个库也不会怎么更新了。
这个库并不是多完善的库,只是封装了一些 API,加上了一些计算方法。
如果需要使用,建议复制代码到项目中,然后根据需求进行修改。
简介
CZGL.SystemInfo 是一个支持 Windows 和 Linux 等平台的能够获取机器硬件信息、采集机器资源信息、监控进程资源的库。
在不引入额外依赖的情况下,使用 .NET Runtime 本身的 API,或通过计算获得信息,提供高性能的计算方式以及缓存,提高性能,还提供 dotnet tool 工具,通过命令行在终端使用。
Windows 可以使用 System.Diagnostics.PerformanceCounter 、System.Management.ManagementObjectSearcher 分别获得性能计算器以及机器的 CPU型号、磁盘序列化号等信息。
平台差异而且很难统一,所以如获取某些硬件的型号序列化,获得进程信息的资源信息,这些需求调用系统相关的API或者使用命令行操作,需要自己定制。
在新版本中,增加了跨平台获取 CPU、内存、网络、磁盘的功能。

预览
CZGL.ProcessMetrics 是一个 Metrics 库,能够将程序的 GC、CPU、内存、机器网络、磁盘空间等信息记录下来,使用 Prometheus 采集信息,然后使用 Grafana 显示。支持 .NET Core 和 .NET Framework 应用,例如 Wpf、Winfrom 应用等。
视频地址:
https://www.bilibili.com/video/BV18y4y1K7Ax/
教程地址:https://github.com/whuanle/CZGL.SystemInfo/blob/primary/docs/Metrics.md





使用在线监控
可通过 Prometheus 采集程序信息,接着使用 Grafana 分析、显示数据。
CZGL.ProcessMetrics 支持 .NET Standard 2.0 和 .NET Core 3.1,但是在 .NET Standard 2.0 中,因为缺少部分 Core API,所以有部分信息是无法获取的,这部分信息如下:
| 标识 | .NET Core API | 说明 | | ---------------------------- | --------------------------- | ---------------- | | gc_memory_info | GC.GetGCMemoryInfo() | 获取 GC 内存信息 | | total_allocated_bytes | GC.GetTotalAllocatedBytes() | 总分配量 | | dotnet_lock_contention_total | Monitor.LockContentionCount | 线程池竞争数量 |
CZGL.ProcessMetrics 支持 .NET Framework 、.NET Core。
使用方法
有两种方式使用 Metrics,第一种是使用内置的 HttpListener,不需要放到 Web 中即可独立提供 URL 访问,适合 winform、wpf 或纯 控制台等应用。但是使用 HttpListener,需要使用管理员方式启动应用才能正常运行。
使用方法:
using CZGL.ProcessMetrics;
... ...
MetricsServer metricsServer = new MetricsServer("http://*:1234/metrics/");
metricsServer.Start();
另外一种是使用 ASP.NET Core,Metrics 作为中间件加入到 Web 应用中,此时使用的是 kestrel 。
在 Nuget 中,搜索 CZGL.ProcessMetrics.ASPNETCore 包,然后使用中间件生成 Metrics 端点。
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.ProcessMetrices("/metrics");
});
但是目前无论哪种,都必须让暴露端口出去,让 Prometheus 能够访问到 API。后期会增加支持不需要暴露 API 、提供 Web 服务,即可直接推送监控信息到 Prometheus 的功能。
访问 /metrics 可以查看到记录的信息。
打开 Prometheus 的 prometheus.yml 文件,在最后加上:
- job_name: 'processmetrice'
metrics_path: '/metrics'
static_configs:
- targets: ['106.12.123.123:1234']
请修改上面的 IP。
然后重启 Prometheus ,打开 Prometheus 的 Status-Targets,即可看到已被加入监控。

按照 https://prometheus.io/docs/visualization/grafana/ 配置好 Prometheus 。
然后下载 CZGL.ProcessMetrics.json 文件,在 Grafana 中导入。


自定义监控指标
你也可以自定义要监控的指标数据。
如果要单独输出 Prometheus 监控数据,你需要引用一个 prometheus.net 包。
但是在 CZGL.ProcessMetrics 中,编写了一个简单的生成器,而无需引用 prometheus.net 包。
你可以通过简单的方式添加自定义的指标数据,发布到 Prometheus 中,然后使用 Grafana 解析出来。
var metrics = ProcessMetricsCore.Instance;
var gauge = metrics.CreateCounter("dotnet_my_metrics","自定义的指标");
var gaugeLabels = gauge.Create();
gcCounterLabels
.AddLabel("name", "test")
.SetValue(6);
视频地址:
https://www.bilibili.com/video/BV18y4y1K7Ax/
教程地址:https://github.com/whuanle/CZGL.SystemInfo/blob/primary/docs/Metrics.md
效果图预览:


多机器多应用效果:

安装 ProcsssMetrics
只需要通过 Nuget 安装一个库,即可快速为程序添加资源监视,接着可将监控数据收集起来,让 Prometheus 被动捕获或主动推送。
支持三种启动方式。
监控 URL
有两种方式使用 Metrics,第一种是使用内置的 HttpListener,不需要放到 Web 中即可独立提供 URL 访问,适合 winform、wpf 或纯 控制台等应用。但是使用 HttpListener,需要使用管理员方式启动应用才能正常运行。
使用方法:
using CZGL.ProcessMetrics;
... ...
MetricsServer metricsServer = new MetricsServer("http://*:1234/metrics/");
metricsServer.Start();
此方式需要暴露端口和 URL ,由 Prometheus 捕获。
ASP.NET Core
另外一种是使用 ASP.NET Core,Metrics 作为中间件加入到 Web 应用中,此时使用的是 kestrel 。
在 Nuget 中,搜索 CZGL.ProcessMetrics.ASPNETCore 包,然后使用中间件生成 Metrics 端点。
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.ProcessMetrices("/metrics");
});
访问相应的 URL,可以看到有很多信息输出,这些都是 Prometheus 数据的格式。
http://127.0.0.1:1234/metrics

主动推送
主动推送方式,可以不需要绑定端口,也不需要暴露 URL,Wpf、Winfrom 应用可以更加方便地推送数据,也可以将外网内网隔离开来。
部署 Pushgateway:
docker run -d \
--name=pg \
-p 9091:9091 \
prom/pushgateway
端口是 9091;也可以使用别的方式部署。
然后在 Prometheus 的 prometheus.yml 文件最后加上:
- job_name: 'linux-pushgateway'
metrics_path: /metrics
static_configs:
- targets: ['172.16.2.101:9091']
推送监控信息:
MetricsPush metricsPush = new MetricsPush("http://127.0.0.1:9091");
var result = await metricsPush.PushAsync();
自定义 EventSource
在 .NET 中,内置了以下 EventSource:
* Microsoft-Windows-DotNETRuntime
* System.Runtime
* Microsoft-System-Net-Http
* System.Diagnostics.Eventing.FrameworkEventSource
* Microsoft-Diagnostics-DiagnosticSource
* Microsoft-System-Net-Sockets
* Microsoft-System-Net-NameResolution
* System.Threading.Tasks.TplEventSource
* System.Buffers.ArrayPoolEventSource
* Microsoft-System-Net-Security
* System.Collections.Concurrent.ConcurrentCollectionsEventSource
这些 Eventsource 是实现 Metrics、Log、Tracing 的绝佳数据来源,例如在 System.Runtime 中,可以获得以下信息:
[System.Runtime]
% Time in GC since last GC (%) 0
Allocation Rate / 1 sec (B) 0
CPU Usage (%) 0
Exception Count / 1 sec 0
GC Heap Size (MB) 4
Gen 0 GC Count / 60 sec 0
Gen 0 Size (B) 0
Gen 1 GC Count / 60 sec 0
Gen 1 Size (B) 0
Gen 2 GC Count / 60 sec 0
Gen 2 Size (B) 0
LOH Size (B) 0
Monitor Lock Contention Count / 1 sec 0
Number of Active Timers 1
Number of Assemblies Loaded 140
ThreadPool Completed Work Item Count / 1 sec 3
ThreadPool Queue Length 0
ThreadPool Thread Count 7
Working Set (MB) 63
在 CZGL.ProcessMetrics 中,默认只监控了 System.Runtime,如果需要捕获其它 EventSource,则可以通过配置添加:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.ProcessMetrices("/metrics", options =>
{
// 监控 CLR 中的事件
options.ListenerNames.Add(EventNames.System_Runtime);
// 监控 ASP.NET Core 中的请求
options.ListenerNames.Add(EventNames.AspNetCore_Http_Connections);
options.ListenerNames.Add("自定义的EventSource名称");
// 无特殊需求,请不要使用
// options.Labels.Add("other", "自定义标识");
// 自定义要监控的数据源,可以自由使用
// options.Assemblies.Add(..);
});
});
另外,你也可以自行添加 EventSource,这些 EventSource 可以使用 dotnet-counter、dotnet-dump 等工具捕获。
你可以参考这里,编写 EventSource:https://github.com/microsoft/dotnet-samples/blob/master/Microsoft.Diagnostics.Tracing/EventSource/docs/EventSource.md
自定义监控数据
在 CZGL.ProcessMetrics 中,内置了一些数据源,这些数据可能来自机器、可能来自应用,但是不一定符合你的需求,你可以自定义添加一些需要的数据指标,例如 wpf 的鼠标点击次数等。
只需要继承 IMerticsSource 接口即可。
示例如下:
public class CLRMetrics : IMerticsSource
{
public async Task InvokeAsync(ProcessMetricsCore metricsCore)
{
await Task.Factory.StartNew(() =>
{
Gauge monitor = metricsCore.CreateGauge("dotnet_lock_contention_total", "Provides a mechanism that synchronizes access to objects.");
monitor.Create()
.AddLabel("process_name","myapp")
.SetValue(Monitor.LockContentionCount);
});
}
}
然后添加需要自定义数据源的程序集,在程序启动时,会主动扫描。
endpoints.ProcessMetrices("/metrics", options =>
{
// 监控 CLR 中的事件
options.ListenerNames.Add(EventNames.System_Runtime);
options.Labels.Add("other", "自定义标识");
// 自定义要监控的数据源
options.Assemblies.Add(typeof(CZGL.ProcessMetrics.MetricsPush).Assembly);
});
搭建 Prometheus/Grafana
这里我们使用 Docker 来搭建监控平台。
拉取镜像:
docker pull prom/prometheus
docker pull grafana/grafana
在 /opt/prometheus 目录下,新建一个 prometheus.yml 文件,其内容如下:
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_config
Related Skills
node-connect
340.5kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
84.2kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
340.5kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
84.2kCommit, push, and open a PR
