prometheus-net

Форк
0
/
DotNetStats.cs 
98 строк · 4.1 Кб
1
using System.Diagnostics;
2

3
namespace Prometheus;
4

5
/// <summary>
6
/// Collects basic .NET metrics about the current process. This is not meant to be an especially serious collector,
7
/// more of a producer of sample data so users of the library see something when they install it.
8
/// </summary>
9
public sealed class DotNetStats
10
{
11
    /// <summary>
12
    /// Registers the .NET metrics in the specified registry.
13
    /// </summary>
14
    public static void Register(CollectorRegistry registry)
15
    {
16
        var instance = new DotNetStats(Metrics.WithCustomRegistry(registry));
17
        registry.AddBeforeCollectCallback(instance.UpdateMetrics);
18
    }
19

20
    /// <summary>
21
    /// Registers the .NET metrics in the default metrics factory and registry.
22
    /// </summary>
23
    internal static void RegisterDefault()
24
    {
25
        var instance = new DotNetStats(Metrics.DefaultFactory);
26
        Metrics.DefaultRegistry.AddBeforeCollectCallback(instance.UpdateMetrics);
27
    }
28

29
    private readonly Process _process;
30
    private readonly List<Counter.Child> _collectionCounts = new List<Counter.Child>();
31
    private Gauge _totalMemory;
32
    private Gauge _virtualMemorySize;
33
    private Gauge _workingSet;
34
    private Gauge _privateMemorySize;
35
    private Counter _cpuTotal;
36
    private Gauge _openHandles;
37
    private Gauge _startTime;
38
    private Gauge _numThreads;
39

40
    private DotNetStats(IMetricFactory metricFactory)
41
    {
42
        _process = Process.GetCurrentProcess();
43

44
        var collectionCountsParent = metricFactory.CreateCounter("dotnet_collection_count_total", "GC collection count", new[] { "generation" });
45

46
        for (var gen = 0; gen <= GC.MaxGeneration; gen++)
47
        {
48
            _collectionCounts.Add(collectionCountsParent.Labels(gen.ToString()));
49
        }
50

51
        // Metrics that make sense to compare between all operating systems
52
        // Note that old versions of pushgateway errored out if different metrics had same name but different help string.
53
        // This is fixed in newer versions but keep the help text synchronized with the Go implementation just in case.
54
        // See https://github.com/prometheus/pushgateway/issues/194
55
        // and https://github.com/prometheus-net/prometheus-net/issues/89
56
        _startTime = metricFactory.CreateGauge("process_start_time_seconds", "Start time of the process since unix epoch in seconds.");
57
        _cpuTotal = metricFactory.CreateCounter("process_cpu_seconds_total", "Total user and system CPU time spent in seconds.");
58

59
        _virtualMemorySize = metricFactory.CreateGauge("process_virtual_memory_bytes", "Virtual memory size in bytes.");
60
        _workingSet = metricFactory.CreateGauge("process_working_set_bytes", "Process working set");
61
        _privateMemorySize = metricFactory.CreateGauge("process_private_memory_bytes", "Process private memory size");
62
        _openHandles = metricFactory.CreateGauge("process_open_handles", "Number of open handles");
63
        _numThreads = metricFactory.CreateGauge("process_num_threads", "Total number of threads");
64

65
        // .net specific metrics
66
        _totalMemory = metricFactory.CreateGauge("dotnet_total_memory_bytes", "Total known allocated memory");
67

68
        _startTime.SetToTimeUtc(_process.StartTime);
69
    }
70

71
    // The Process class is not thread-safe so let's synchronize the updates to avoid data tearing.
72
    private readonly object _updateLock = new object();
73

74
    private void UpdateMetrics()
75
    {
76
        try
77
        {
78
            lock (_updateLock)
79
            {
80
                _process.Refresh();
81

82
                for (var gen = 0; gen <= GC.MaxGeneration; gen++)
83
                    _collectionCounts[gen].IncTo(GC.CollectionCount(gen));
84

85
                _totalMemory.Set(GC.GetTotalMemory(false));
86
                _virtualMemorySize.Set(_process.VirtualMemorySize64);
87
                _workingSet.Set(_process.WorkingSet64);
88
                _privateMemorySize.Set(_process.PrivateMemorySize64);
89
                _cpuTotal.IncTo(_process.TotalProcessorTime.TotalSeconds);
90
                _openHandles.Set(_process.HandleCount);
91
                _numThreads.Set(_process.Threads.Count);
92
            }
93
        }
94
        catch (Exception)
95
        {
96
        }
97
    }
98
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.