|
18 | 18 |
|
19 | 19 | using System; |
20 | 20 | using Microsoft.AspNetCore.Http; |
| 21 | +using Microsoft.AspNetCore.Routing; |
21 | 22 | using Microsoft.Extensions.DependencyInjection; |
22 | 23 | using OpenTelemetry.Exporter; |
23 | 24 | using OpenTelemetry.Exporter.Prometheus; |
@@ -149,6 +150,52 @@ public static IApplicationBuilder UseOpenTelemetryPrometheusScrapingEndpoint( |
149 | 150 | builder.UseMiddleware<PrometheusExporterMiddleware>(meterProvider); |
150 | 151 | }); |
151 | 152 | } |
| 153 | + |
| 154 | + /// <summary> |
| 155 | + /// Adds OpenTelemetry Prometheus scraping endpoint middleware to an |
| 156 | + /// <see cref="IEndpointRouteBuilder"/> instance. |
| 157 | + /// </summary> |
| 158 | + /// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add |
| 159 | + /// middleware to.</param> |
| 160 | + /// <param name="path">Optional path to use for the branched pipeline.</param> |
| 161 | + /// <param name="meterProvider">Optional <see cref="MeterProvider"/> |
| 162 | + /// containing a <see cref="PrometheusExporter"/> otherwise the primary |
| 163 | + /// SDK provider will be resolved using application services.</param> |
| 164 | + /// <param name="configureBranchedPipeline">Optional callback to |
| 165 | + /// configure the branched pipeline. Called before registration of the |
| 166 | + /// Prometheus middleware.</param> |
| 167 | + /// <returns>A convention routes for the Prometheus scraping endpoint.</returns> |
| 168 | + public static IEndpointConventionBuilder MapPrometheusScrapingEndpoint( |
| 169 | + this IEndpointRouteBuilder endpoints, |
| 170 | + string path = null, |
| 171 | + MeterProvider meterProvider = null, |
| 172 | + Action<IApplicationBuilder> configureBranchedPipeline = null) |
| 173 | + { |
| 174 | + var builder = endpoints.CreateApplicationBuilder(); |
| 175 | + |
| 176 | + // Note: Order is important here. MeterProvider is accessed before |
| 177 | + // GetOptions<PrometheusExporterOptions> so that any changes made to |
| 178 | + // PrometheusExporterOptions in deferred AddPrometheusExporter |
| 179 | + // configure actions are reflected. |
| 180 | + meterProvider ??= builder.ApplicationServices.GetRequiredService<MeterProvider>(); |
| 181 | + |
| 182 | + if (path == null) |
| 183 | + { |
| 184 | + var options = builder.ApplicationServices.GetOptions<PrometheusExporterOptions>(); |
| 185 | + path = options.ScrapeEndpointPath ?? PrometheusExporterOptions.DefaultScrapeEndpointPath; |
| 186 | + } |
| 187 | + |
| 188 | + if (!path.StartsWith("/")) |
| 189 | + { |
| 190 | + path = $"/{path}"; |
| 191 | + } |
| 192 | + |
| 193 | + configureBranchedPipeline?.Invoke(builder); |
| 194 | + |
| 195 | + builder.UseMiddleware<PrometheusExporterMiddleware>(meterProvider); |
| 196 | + |
| 197 | + return endpoints.Map(new PathString(path), builder.Build()); |
| 198 | + } |
152 | 199 | } |
153 | 200 | } |
154 | 201 | #endif |
0 commit comments