一个.NET Core 监控系统用于监控 CPU 内存等信息的工具
由于 .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
效果图预览:
多机器多应用效果:
只需要通过 Nuget 安装一个库,即可快速为程序添加资源监视,接着可将监控数据收集起来,让 Prometheus 被动捕获或主动推送。
支持三种启动方式。
有两种方式使用 Metrics,第一种是使用内置的 HttpListener,不需要放到 Web 中即可独立提供 URL 访问,适合 winform、wpf 或纯 控制台等应用。但是使用 HttpListener,需要使用管理员方式启动应用才能正常运行。
使用方法:
using CZGL.ProcessMetrics;
... ...
MetricsServer metricsServer = new MetricsServer("http://*:1234/metrics/");
metricsServer.Start();此方式需要暴露端口和 URL ,由 Prometheus 捕获。
另外一种是使用 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();在 .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 中,可以获得以下信息:
…在 CZGL.ProcessMetrics 中,默认只监控了 System.Runtime,如果需要捕获其它 EventSource,则可以通过配置添加:
…另外,你也可以自行添加 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);
});这里我们使用 Docker 来搭建监控平台。
拉取镜像:
docker pull prom/prometheus
docker pull grafana/grafana 在 /opt/prometheus 目录下,新建一个 prometheus.yml 文件,其内容如下:
…请替换最后一行的 IP。
使用容器启动 Prometheus:
docker run -d -p 9090:9090 -v /opt/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus使用容器启动 Grafana:
mkdir /opt/grafana-storage
chmod 777 -R /opt/grafana-storage
docker run -d -p 3000:3000 --name=grafana -v /opt/grafana-storage:/var/lib/grafana grafana/grafana打开 9090 端口,在菜单栏中打开 Status-Targets,可以看到有相关记录。
接着,访问 3000 端口,打开 Grafana,初始账号密码都是 admin 。
首先我们要为 Grafana 获取 Prometheus 中的监控数据,我们要添加一个数据源。
选择 Prometheus,按照提示,填写好 HTTP-URL 即可。
接着,下载笔者定制好的 Jsom Model,文件名为 CZGL.ProcessMetrics.json。
下载地址: https://github.com/whuanle/CZGL.SystemInfo/releases/tag/v1.0
然后导入模型文件。
即可看到监控界面。
目前做了个简单的 dotnet 工具,无需 SDK,runtime 下即可使用。
安装命令:
dotnet tool install --global csys
# or
dotnet tool install --global csys --version 1.0.3You can invoke the tool using the following command: csys
Tool 'csys' (version '1.0.2') was successfully installed.如果在 Linux 下,安装,还需要设置环境变量:
export PATH="$PATH:/home/{你的用户名}/.dotnet/tools"安装完毕后,输入命令进入小工具:
csys请输入命令
+-------命令参考------------------------------+
| 1. 输入 netinfo 查看网络详情 |
| 2. 输入 nett 监控网络流量 |
| 3. 输入 test ,检查当前操作系统不兼容哪些 API |
| 4. 输入 ps 查看进程信息 |
+---------------------------------------------+注:需要使用超级管理员启动程序,才能使用 ps 功能;
动图:
小工具功能不多,有兴趣可以下载 Nuget 包,里面有更多功能。
CZGL.SystemInfo 目前有四个类:DiskInfo、NetworkInfo、ProcessInfo、SystemPlatformInfo,下面一一介绍。
为了避免资源浪费,DiskInfo、NetworkInfo、ProcessInfo 部分属性使用懒加载,不使用此 API 的情况下,不需要消耗性能。
Install-Package CZGL.SystemInfo -Version 1.0.1静态类,能够获取运行环境信息和有限的硬件信息,所有信息在程序启动前就已经确定。
其 API 说明及获得的数据示例如下:
| 属性 | 说明 | Windows 示例 | Linux 示例 |
|---|---|---|---|
| FrameworkDescription | 框架平台(.NET Core、Mono等)信息 | .NET Core 3.1.9 | .NET Core 3.1.9 |
| FrameworkVersion | 运行时信息版本 | 3.1.9 | 3.1.9 |
| OSArchitecture | 操作系统平台架构 | X64 | X64 |
| OSPlatformID | 获取操作系统的类型 | Win32NT | Unix |
| OSVersion | 操作系统内核版本 | Microsoft Windows NT 6.2.9200.0 | Unix 4.4.0.19041 |
| OSDescription | 操作系统的版本描述 | Microsoft Windows 10.0.19041 | Linux 4.4.0-19041-Microsoft #488-Microsoft Mon Sep 01 13:43:00 PST 2020 |
| ProcessArchitecture | 本进程的架构 | X64 | X64 |
| ProcessorCount | 当前计算机上的处理器数 | 8 | 8 |
| MachineName | 计算机名称 | dell-PC | dell-PC |
| UserName | 当前登录到此系统的用户名称 | dell | dell |
| UserDomainName | 用户网络域名称 | dell-PC | dell-PC |
| IsUserInteractive | 是否在交互模式中运行 | True | True |
| GetLogicalDrives | 系统的磁盘和分区列表 | C:,D:, E:, F:, G:\ | /, /dev, /sys, /proc, /dev/pts, /run, /run/shm |
| SystemDirectory | 系统根目录完全路径 | X:\WINDOWS\system32 | |
| MemoryPageSize | 操作系统内存页一页的字节数 | 4096 | 4096 |
SystemPlatformInfo 的 API 不会有跨平台不兼容问题,可以大胆使用。
效果演示:
系统平台信息:
运行框架 : .NET Core 3.1.0
操作系统 : Microsoft Windows 10.0.17763
操作系统版本 : Microsoft Windows NT 6.2.9200.0
平台架构 : X64
机器名称 : aaaa-PC
当前关联用户名 : aaa
用户网络域名 : aaa-PC
系统已运行时间(毫秒) : 3227500
Web程序核心框架版本 :暂无开放 Issues,或尚未同步最近议题。