diff --git a/src/Prometheus.Client.AspNetCore/PrometheusExtensions.cs b/src/Prometheus.Client.AspNetCore/PrometheusExtensions.cs index 720b17f..4e3329b 100644 --- a/src/Prometheus.Client.AspNetCore/PrometheusExtensions.cs +++ b/src/Prometheus.Client.AspNetCore/PrometheusExtensions.cs @@ -1,7 +1,9 @@ -using System; +using System; +using System.Net; using System.Threading.Tasks; using Prometheus.Client.Collectors; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; namespace Prometheus.Client.AspNetCore { @@ -36,8 +38,8 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a throw new ArgumentException($"MapPath '{options.MapPath}' should start with '/'"); RegisterCollectors(options); - - app.Map(options.MapPath, coreapp => + + Action addMetricsHandler = coreapp => { coreapp.Run(async context => { @@ -51,9 +53,15 @@ public static IApplicationBuilder UsePrometheusServer(this IApplicationBuilder a await Task.FromResult(0).ConfigureAwait(false); }); - }); + }; + + if (options.Port == null) + { + return app.Map(options.MapPath, addMetricsHandler); + } - return app; + Func portMatches = context => context.Connection.LocalPort == options.Port; + return app.Map(options.MapPath, cfg => cfg.MapWhen(portMatches, addMetricsHandler)); } @@ -61,8 +69,8 @@ private static void RegisterCollectors(PrometheusOptions options) { if (options.UseDefaultCollectors) { - var metricFactory = options.CollectorRegistryInstance == CollectorRegistry.Instance - ? Metrics.DefaultFactory + var metricFactory = options.CollectorRegistryInstance == CollectorRegistry.Instance + ? Metrics.DefaultFactory : new MetricFactory(options.CollectorRegistryInstance); options.Collectors.AddRange(DefaultCollectors.Get(metricFactory)); diff --git a/src/Prometheus.Client.AspNetCore/PrometheusOptions.cs b/src/Prometheus.Client.AspNetCore/PrometheusOptions.cs index 98f6dfc..fc37bd9 100644 --- a/src/Prometheus.Client.AspNetCore/PrometheusOptions.cs +++ b/src/Prometheus.Client.AspNetCore/PrometheusOptions.cs @@ -14,6 +14,11 @@ public class PrometheusOptions /// public string MapPath { get; set; } = "/metrics"; + /// + /// When specified only allow access to metrics on this port, otherwise return 404, default = null. + /// + public int? Port { get; set; } + /// /// CollectorRegistry intance /// @@ -29,4 +34,4 @@ public class PrometheusOptions /// public bool UseDefaultCollectors { get; set; } = true; } -} \ No newline at end of file +}