prometheus-net

Форк
0
/
MetricServerMiddlewareExtensions.cs 
131 строка · 4.9 Кб
1
using Microsoft.AspNetCore.Builder;
2
using Microsoft.AspNetCore.Http;
3
using Microsoft.AspNetCore.Routing;
4
using System.ComponentModel;
5

6
namespace Prometheus;
7

8
public static class MetricServerMiddlewareExtensions
9
{
10
    private const string DefaultDisplayName = "Prometheus metrics";
11

12
    /// <summary>
13
    /// Starts a Prometheus metrics exporter using endpoint routing.
14
    /// The default URL is /metrics, which is a Prometheus convention.
15
    /// Use static methods on the <see cref="Metrics"/> class to create your metrics.
16
    /// </summary>
17
    public static IEndpointConventionBuilder MapMetrics(
18
        this IEndpointRouteBuilder endpoints,
19
        Action<MetricServerMiddleware.Settings> configure,
20
        string pattern = "/metrics"
21
    )
22
    {
23
        var pipeline = endpoints
24
            .CreateApplicationBuilder()
25
            .InternalUseMiddleware(configure)
26
            .Build();
27

28
        return endpoints
29
            .Map(pattern, pipeline)
30
            .WithDisplayName(DefaultDisplayName);
31
    }
32

33
    /// <summary>
34
    /// Starts a Prometheus metrics exporter, filtering to only handle requests received on a specific port.
35
    /// The default URL is /metrics, which is a Prometheus convention.
36
    /// Use static methods on the <see cref="Metrics"/> class to create your metrics.
37
    /// </summary>
38
    public static IApplicationBuilder UseMetricServer(
39
        this IApplicationBuilder builder,
40
        int port,
41
        Action<MetricServerMiddleware.Settings> configure,
42
        string? url = "/metrics")
43
    {
44
        // If no URL, use root URL.
45
        url ??= "/";
46

47
        return builder
48
            .Map(url, b => b.MapWhen(PortMatches(), b1 => b1.InternalUseMiddleware(configure)));
49

50
        Func<HttpContext, bool> PortMatches()
51
        {
52
            return c => c.Connection.LocalPort == port;
53
        }
54
    }
55

56
    /// <summary>
57
    /// Starts a Prometheus metrics exporter.
58
    /// The default URL is /metrics, which is a Prometheus convention.
59
    /// Use static methods on the <see cref="Metrics"/> class to create your metrics.
60
    /// </summary>
61
    public static IApplicationBuilder UseMetricServer(
62
        this IApplicationBuilder builder,
63
        Action<MetricServerMiddleware.Settings> configure,
64
        string? url = "/metrics")
65
    {
66
        if (url != null)
67
            return builder.Map(url, b => b.InternalUseMiddleware(configure));
68
        else
69
            return builder.InternalUseMiddleware(configure);
70
    }
71

72
    #region Legacy methods without the configure action
73
    /// <summary>
74
    /// Starts a Prometheus metrics exporter using endpoint routing.
75
    /// The default URL is /metrics, which is a Prometheus convention.
76
    /// Use static methods on the <see cref="Metrics"/> class to create your metrics.
77
    /// </summary>
78
    [EditorBrowsable(EditorBrowsableState.Never)] // It is not exactly obsolete but let's de-emphasize it.
79
    public static IEndpointConventionBuilder MapMetrics(
80
        this IEndpointRouteBuilder endpoints,
81
        string pattern = "/metrics",
82
        CollectorRegistry? registry = null
83
    )
84
    {
85
        return MapMetrics(endpoints, LegacyConfigure(registry), pattern);
86
    }
87

88
    /// <summary>
89
    /// Starts a Prometheus metrics exporter, filtering to only handle requests received on a specific port.
90
    /// The default URL is /metrics, which is a Prometheus convention.
91
    /// Use static methods on the <see cref="Metrics"/> class to create your metrics.
92
    /// </summary>
93
    [EditorBrowsable(EditorBrowsableState.Never)] // It is not exactly obsolete but let's de-emphasize it.
94
    public static IApplicationBuilder UseMetricServer(
95
        this IApplicationBuilder builder,
96
        int port,
97
        string? url = "/metrics",
98
        CollectorRegistry? registry = null)
99
    {
100
        return UseMetricServer(builder, port, LegacyConfigure(registry), url);
101
    }
102

103
    /// <summary>
104
    /// Starts a Prometheus metrics exporter.
105
    /// The default URL is /metrics, which is a Prometheus convention.
106
    /// Use static methods on the <see cref="Metrics"/> class to create your metrics.
107
    /// </summary>
108
    [EditorBrowsable(EditorBrowsableState.Never)] // It is not exactly obsolete but let's de-emphasize it.
109
    public static IApplicationBuilder UseMetricServer(
110
        this IApplicationBuilder builder,
111
        string? url = "/metrics",
112
        CollectorRegistry? registry = null)
113
    {
114
        return UseMetricServer(builder, LegacyConfigure(registry), url);
115
    }
116

117
    private static Action<MetricServerMiddleware.Settings> LegacyConfigure(CollectorRegistry? registry) =>
118
        (MetricServerMiddleware.Settings settings) =>
119
        {
120
            settings.Registry = registry;
121
        };
122
    #endregion
123

124
    private static IApplicationBuilder InternalUseMiddleware(this IApplicationBuilder builder, Action<MetricServerMiddleware.Settings> configure)
125
    {
126
        var settings = new MetricServerMiddleware.Settings();
127
        configure(settings);
128

129
        return builder.UseMiddleware<MetricServerMiddleware>(settings);
130
    }
131
}
132

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

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

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

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