为你的 .NET 应用加个监控 ---- CZGL.ProcessMetrics

时间:2021-07-22
本文章向大家介绍为你的 .NET 应用加个监控 ---- CZGL.ProcessMetrics,主要包括为你的 .NET 应用加个监控 ---- CZGL.ProcessMetrics使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

导读

CZGL.ProcessMetrics 是一个 Metrics 库,能够将程序的 GC、CPU、内存、机器网络、磁盘空间等信息记录下来,使用 Prometheus 采集信息,然后使用 Grafana 显示。

视频地址:

https://www.bilibili.com/video/BV18y4y1K7Ax/

效果图预览:

安装 ProcsssMetrics

只需要通过 Nuget 安装一个库,即可快速为程序添加资源监视,ProcssMetrics 同时支持 Winform、Wpf、ASP.NET Core 等。
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 线程池竞争数量

新建一个应用, Nuget 中搜索 CZGL.ProcessMetrics 直接引用即可。

Nuget 地址:https://www.nuget.org/packages/CZGL.ProcessMetrics

有两种方式使用 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 的功能。

访问相应的 URL,可以看到有很多信息输出,这些都是 Prometheus 数据的格式。

http://127.0.0.1:1234/metrics

搭建 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_configs:
    - targets:
      # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
    - targets: ['localhost:9090']


  - job_name: 'processmetrice'
    metrics_path: '/metrics'
    static_configs:
    - targets: ['123.123.123.123:1234']

请替换最后一行的 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

首先我们要为 Grafana 获取 Prometheus 中的监控数据,我们要添加一个数据源。

选择 Prometheus,按照提示,填写好 HTTP-URL 即可。

接着,下载笔者定制好的 Jsom Model,文件名为 CZGL.ProcessMetrics.json

下载地址:
https://github.com/whuanle/CZGL.SystemInfo/releases/tag/v1.0

然后导入模型文件。

即可看到监控界面。

出处:https://www.cnblogs.com/whuanle/p/14969982.html

=======================================================================================

导读

CZGL.ProcessMetrics 是一个 Metrics 库,能够将程序的 GC、CPU、内存、机器网络、磁盘空间等信息记录下来,使用 Prometheus 采集信息,然后使用 Grafana 显示。

周日花了时间把这个库更新,修复了一些 Bug,增加了一些有趣的功能,支持多服务器多应用,支持 wpf、winfrom、.NET Core 等应用,在不需要暴露端口的情况下,也可以推送监控数据到 Prometheus,支持自定义数据源。

另外对 Grafana 模板进行了一些优化,增加了一些数据源。

根据机器、应用等选择需要显示的数据:

三种方式处理监控数据

详细文档请参考:

https://github.com/whuanle/CZGL.SystemInfo/blob/primary/docs/Metrics.md

主动推送

第一种需要使用 Pushgateway,Pushgateway 允许任何客户端向其推送符合规范的自定义监控指标,再使用 Prometheus 统一收集监控。

我们不必把应用的监控数据都推送到 Prometheus,而是推送到 Pushgateway,多个应用一起推送,然后Prometheus 定期一次性获取。

示例代码如下:

            MetricsPush metricsPush = new MetricsPush("http://123.12.1.2:9091");
            while (true)
            {
                var code = metricsPush.PushAsync().Result;
                // 如果 code 不是 200,请检查推送的地址有没有错误,或联系笔者讨论
                // 自定义推送间隔时间
                Thread.Sleep(1000);
            }

这种方法适合非 Web 应用、不能暴露端口的应用、内网应用或者 Winfrom、Wpf 这类应用使用。

ASP.NET Core

在 Nuget 中,搜索 CZGL.ProcessMetrics.ASPNETCore 包,然后使用中间件生成 Metrics 端点。

endpoints.ProcessMetrices("/metrics", options =>
{
// 监控 CLR 中的事件
options.ListenerNames.Add(EventNames.System_Runtime);
// options.Labels.Add("other", "自定义标识");

// 自定义要监控的数据源 
options.Assemblies.Add(typeof(CZGL.ProcessMetrics.MetricsPush).Assembly);
});

或:

endpoints.ProcessMetrices("/metrics");

自定义URL

自定义 HTTP Server,暴露一个 URL ,供 Prometheus 抓取。

new Thread(() =>
{
MetricsServer metricsServer = new MetricsServer("http://*:1234/metrics/");
metricsServer.Start();
}).Start();

.NET diagnostics

在程序出现内存泄漏或者 CPU 太高的时候,有没有使用过 dotnet-tool 来排查?例如 dotnet-counter、dotnet-dump。

这些工具可以获得详细的 EvenSource 信息:

[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 中,也可以监控这些指标啦~

在 .NET 中,内置了一些 EventSource,读者可以参考:https://docs.microsoft.com/en-us/dotnet/core/diagnostics/available-counters#microsoftaspnetcorehttpconnections-counters

常见的 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

在 CZGL.ProcessMetrics 中 ,默认只监控了 System.Runtime,你也可以添加更多类型的 EventSource,甚至是你自定义的 EventSource。

在配置的时候,使用即可:

endpoints.ProcessMetrices("/metrics", options =>
{
// 监控 CLR 中的事件
options.ListenerNames.Add(EventNames.System_Runtime);
options.ListenerNames.Add(EventNames.AspNetCore_Http_Connections);
}
MetricsPush metricsPush = new MetricsPush(url: "http://123.1.1.2:9091",
option: options =>
{
// 监控 CLR 中的事件
options.ListenerNames.Add(EventNames.System_Runtime);
options.ListenerNames.Add(EventNames.AspNetCore_Http_Connections);
});

自定义监控指标

如果你有一些指标数据,也要放到 Grafana 上显示,例如用户鼠标点击次数、并发请求数量等,可以很容易地添加进去:

    public class CLRMetrics : IMerticsSource
    {
        public async Task InvokeAsync(ProcessMetricsCore metricsCore)
        {
            await Task.Factory.StartNew(() =>
            {
                Gauge monitor = metricsCore.CreateGauge("指标名称", "指标描述");
                monitor.Create()
                .AddLabel("自定义标签",value.ToString())    
                .SetValue(Monitor.LockContentionCount);
            });
        }
    }

自定义的数据源,需要继承 IMerticsSource 接口。

目前支持 Counter、Gauge 两种形式的数据,Counter 是累加器,适合不断增加的数据;Gauge 则是自由的数据。

自定义标识用于显示一些特定的信息,Value 则显示具体的值,Label 可以定义多个,但是 Value 只会出现一次。例如:

.AddLabel("磁盘名称","D:\")
.AddLabel("已用空间","58091110")	// 单位 Byte,即 55.40 GB
.AddValue(0)					   // 有时我们只需要显示 Label,不需要 Value,则随便填一个


这个库只是一个简单的工具,相对于专业的 Metrics 工具,指标数据不多,好就好在体积小,使用简单。。。这个库没什么复杂的功能,几行代码就可以跑起来了,小应用用起来方便,不需要什么成本就可以搭建起一个简单的监控。

大佬轻喷。

详细文档可以参考:

https://github.com/whuanle/CZGL.SystemInfo/blob/primary/docs/Metrics.md

项目地址:

https://github.com/whuanle/CZGL.SystemInfo

需要补充 .NET 监控指标或者定制 Grafana 界面,可联系笔者一起讨论~

出处:https://www.cnblogs.com/whuanle/p/15027334.html

您的资助是我最大的动力!
金额随意,欢迎来赏!
款后有任何问题请给我留言。

如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的推荐按钮。
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的关注我。(●'◡'●)

如果你觉得本篇文章对你有所帮助,请给予我更多的鼓励,求打             付款后有任何问题请给我留言!!!

因为,我的写作热情也离不开您的肯定支持,感谢您的阅读,我是【Jack_孟】!

原文地址:https://www.cnblogs.com/mq0036/p/15043921.html