示例#1
0
        public static void BuildMetricsCollector(IConfigurationRoot configuration)
        {
            bool collectMetrics = configuration.GetValue("CollectMetrics", false);

            if (collectMetrics)
            {
                IConfiguration metricsConfigurationSection = configuration.GetSection("Metrics");
                string         metricsStoreType            = metricsConfigurationSection.GetValue <string>("MetricsStoreType");

                if (metricsStoreType == "influxdb")
                {
                    string       metricsDbName    = metricsConfigurationSection.GetValue("MetricsDbName", "metricsdatabase");
                    string       influxDbUrl      = metricsConfigurationSection.GetValue("InfluxDbUrl", "http://influxdb:8086");
                    IMetricsRoot metricsCollector = new MetricsBuilder()
                                                    .Report.ToInfluxDb(
                        options =>
                    {
                        options.InfluxDb.BaseUri  = new Uri(influxDbUrl);
                        options.InfluxDb.Database = metricsDbName;
                        options.InfluxDb.CreateDataBaseIfNotExists = true;
                        options.FlushInterval = TimeSpan.FromSeconds(10);
                    }
                        ).Build();
                    MetricsCollector = Option.Some(metricsCollector);
                    StartReporting(metricsCollector);
                }
                else
                {
                    string       metricsStoreLocation = metricsConfigurationSection.GetValue("MetricsStoreLocation", "metrics");
                    bool         appendToMetricsFile  = metricsConfigurationSection.GetValue("MetricsStoreAppend", false);
                    IMetricsRoot metricsCollector     = new MetricsBuilder()
                                                        .Report.ToTextFile(
                        options =>
                    {
                        options.MetricsOutputFormatter  = new MetricsJsonOutputFormatter();
                        options.AppendMetricsToTextFile = appendToMetricsFile;
                        options.FlushInterval           = TimeSpan.FromSeconds(20);
                        options.OutputPathAndFileName   = metricsStoreLocation;
                    }
                        ).Build();
                    MetricsCollector = Option.Some(metricsCollector);
                    StartReporting(metricsCollector);
                }
            }
        }
示例#2
0
        public void When_using_http_reporter_with_setup_action_flush_interval_greater_than_zero_should_apply()
        {
            // Arrange
            var uri           = "http://localhost/metrics";
            var flushInterval = TimeSpan.FromSeconds(1);
            var builder       = new MetricsBuilder().Report.OverHttp(
                options =>
            {
                options.HttpSettings.RequestUri = new Uri(uri);
                options.FlushInterval           = flushInterval;
            });

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.First().FlushInterval.Should().Be(flushInterval);
        }
示例#3
0
        public void When_using_http_reporter_with_setup_action_flush_interval_equal_to_zero_should_apply_default_interval()
        {
            // Arrange
            var uri           = "http://localhost/metrics";
            var flushInterval = TimeSpan.Zero;
            var builder       = new MetricsBuilder().Report.OverHttp(
                options =>
            {
                options.HttpSettings.RequestUri = new Uri(uri);
                options.FlushInterval           = flushInterval;
            });

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.First().FlushInterval.Should().Be(AppMetricsConstants.Reporting.DefaultFlushInterval);
        }
示例#4
0
        public void Can_set_http_reporter_metrics_filter()
        {
            // Arrange
            var uri     = "http://localhost/metrics";
            var filter  = new MetricsFilter().WhereType(MetricType.Apdex);
            var builder = new MetricsBuilder().Report.OverHttp(
                options =>
            {
                options.HttpSettings.RequestUri = new Uri(uri);
                options.Filter = filter;
            });

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.First().Filter.Should().BeSameAs(filter);
        }
        private void TestBuilderPathWithMetricsEnabled()
        {
            IMetrics metrics = new MetricsBuilder().Build();

            SessionFactory.NewBuilder(TestProductId, TestServiceId)
            .WithInMemoryMetastore()
            .WithNeverExpiredCryptoPolicy()
            .WithStaticKeyManagementService(TestStaticMasterKey)
            .WithMetrics(metrics)
            .Build();

            MetricsUtil.MetricsInstance.Measure.Meter.Mark(new MeterOptions {
                Name = "should.record"
            }, 1);

            // Verify metrics were recorded
            Assert.NotEmpty(MetricsUtil.MetricsInstance.Snapshot.Get().Contexts);
        }
        private static void AddMetrics(IContainer container, string appName)
        {
            if (_metrics != null)
            {
                container.RegisterNonScopedSingleton <IMetrics>(_metrics);
                return;
            }

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("metricsettings.json")
                                .Build();

            var influxOptions = new MetricsReportingInfluxDbOptions();

            configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions);

            var metricsRoot = new MetricsBuilder()
                              .Configuration.ReadFrom(configuration)
                              .Configuration.Configure(
                options =>
            {
                options.AddServerTag();
                options.AddAppTag(appName);
            })
                              .Report.ToInfluxDb(influxOptions)
                              .Build();


            var metrics = new DotNetWorkQueue.AppMetrics.Metrics(metricsRoot);

            container.RegisterNonScopedSingleton <IMetrics>(metrics);

            var scheduler = new AppMetricsTaskScheduler(
                TimeSpan.FromSeconds(3),
                async() =>
            {
                await Task.WhenAll(metricsRoot.ReportRunner.RunAllAsync());
            });

            scheduler.Start();
            _metricScheduler = scheduler;
            _metrics         = metrics;
        }
        public void When_using_console_reporter_with_setup_action_flush_interval_less_than_zero_should_throw()
        {
            // Arrange
            Action action = () =>
            {
                // Act
                var flushInterval = TimeSpan.FromSeconds(-1);
                var builder       = new MetricsBuilder().Report.ToConsole(
                    options =>
                {
                    options.FlushInterval = flushInterval;
                });

                var unused = builder.Build();
            };

            // Assert
            action.Should().Throw <InvalidOperationException>();
        }
        public void When_using_socket_reporter_with_setu_actions_flush_interval_equal_to_zero_should_apply_default_interval()
        {
            // Arrange
            var flushInterval = TimeSpan.Zero;
            var settings      = new SocketSettings(defaultProtocol, defaultAddress, defaultPort);
            var builder       = new MetricsBuilder().Report.OverTcp(
                options =>
            {
                options.FlushInterval          = flushInterval;
                options.MetricsOutputFormatter = new TestMetricsFormatter();
                options.SocketSettings         = settings;
            });

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.First().FlushInterval.Should().Be(AppMetricsConstants.Reporting.DefaultFlushInterval);
        }
示例#9
0
        private static void Init()
        {
            var configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");

            Configuration = configurationBuilder.Build();

            Log.Logger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.LiterateConsole().CreateLogger();

            var metricsConfigSection = Configuration.GetSection(nameof(MetricsOptions));

            Metrics = new MetricsBuilder().Configuration.Configure(metricsConfigSection.AsEnumerable()).Report.ToStatsDUdp(
                opt =>
            {
                opt.SocketSettings.Address = "localhost";
                opt.SocketSettings.Port    = 8125;
            }).Build();

            Reporter = Metrics.ReportRunner;
        }
示例#10
0
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var Metrics = AppMetrics.CreateDefaultBuilder()
                          .OutputMetrics.AsPrometheusPlainText()
                          .OutputMetrics.AsPrometheusProtobuf()
                          .Build();

            var filter  = new MetricsFilter().WhereType(App.Metrics.MetricType.Timer);
            var metrics = new MetricsBuilder()
                          .Report.ToInfluxDb(
                options => {
                options.InfluxDb.BaseUri                   = new Uri("http://127.0.0.1:8086");
                options.InfluxDb.Database                  = "defaultdb";
                options.InfluxDb.Consistenency             = "admin";
                options.InfluxDb.UserName                  = "******";
                options.InfluxDb.Password                  = "******";
                options.InfluxDb.RetentionPolicy           = "rp";
                options.InfluxDb.CreateDataBaseIfNotExists = true;
                options.HttpPolicy.BackoffPeriod           = TimeSpan.FromSeconds(30);
                options.HttpPolicy.FailuresBeforeBackoff   = 5;
                options.HttpPolicy.Timeout                 = TimeSpan.FromSeconds(10);
                options.MetricsOutputFormatter             = new MetricsInfluxDbLineProtocolOutputFormatter();
                options.Filter        = filter;
                options.FlushInterval = TimeSpan.FromSeconds(20);
            })
                          .Build();

            return(Host.CreateDefaultBuilder(args)
                   .ConfigureMetrics(Metrics)
                   .UseMetrics(
                       options =>
            {
                options.EndpointOptions = endpointsOptions =>
                {
                    endpointsOptions.MetricsTextEndpointOutputFormatter = Metrics.OutputMetricsFormatters.OfType <MetricsPrometheusTextOutputFormatter>().First();
                    endpointsOptions.MetricsEndpointOutputFormatter = Metrics.OutputMetricsFormatters.OfType <MetricsPrometheusProtobufOutputFormatter>().First();
                };
            })
                   .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup <Startup>();
            }));
        }
示例#11
0
        public void Can_set_options_with_instance()
        {
            // Arrange
            var options = new MetricsOptions();

            options.Enabled = true;
            options.GlobalTags.Add("tag1", "value1");
            options.DefaultContextLabel = "test";

            // Act
            var metrics = new MetricsBuilder().Configuration.Configure(options).Build();

            // Assert
            metrics.Options.DefaultContextLabel.Should().Be("test");
            metrics.Options.GlobalTags.Count.Should().Be(1);
            metrics.Options.GlobalTags.First().Key.Should().Be("tag1");
            metrics.Options.GlobalTags.First().Value.Should().Be("value1");
            metrics.Options.Enabled.Should().BeTrue();
        }
        static async Task Main(string[] args)
        {
            var metrics = new MetricsBuilder()
                          .Report.OverUdp(
                options =>
            {
                options.SocketSettings.Address = "localhost";
                options.SocketSettings.Port    = 11000;
                options.MetricsOutputFormatter = new MyOutputFormatter(new MetricsTextOptions()
                {
                    Encoding            = System.Text.Encoding.UTF8,
                    MetricNameFormatter = (metricContext, metricName) => metricName,
                    Padding             = 0,
                    Separator           = "",
                });
                //options.Filter = filter;
                //options.FlushInterval = TimeSpan.FromSeconds(config.Value.FlushIntervalInSeconds);
                options.SocketPolicy = new SocketPolicy();
            }
                )
                          .Build();

            Program program1 = new Program();

            program1.StartReporting += Program1_StartReporting1;

            program1.Start(metrics);

            var counter = new CounterOptions {
                Name = "my_counter"
            };

            metrics.Measure.Counter.Increment(counter);

            var counter2 = new CounterOptions {
                Name = "my_counter2"
            };

            metrics.Measure.Counter.Increment(counter2);

            Console.ReadKey();
        }
示例#13
0
        public void Can_use_http_reporter_with_authorization_token()
        {
            // Arrange
            var builder = new MetricsBuilder().Report.OverHttp(
                options =>
            {
                options.HttpSettings.AuthorizationToken = "test";
                options.HttpSettings.RequestUri         = new Uri("http://localhost");
                options.MetricsOutputFormatter          = new MetricsJsonOutputFormatter();
            });

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.Should().Contain(reportMetrics => reportMetrics is HttpMetricsReporter);
            metrics.Reporters.First().FlushInterval.Should().Be(AppMetricsConstants.Reporting.DefaultFlushInterval);
            metrics.Reporters.First().Filter.Should().BeOfType <NullMetricsFilter>();
            metrics.Reporters.First().Formatter.Should().BeOfType <MetricsJsonOutputFormatter>();
        }
示例#14
0
        public void Can_set_options_via_setup_action()
        {
            // Arrange
            void SetupAction(MetricsOptions options)
            {
                options.Enabled = false;
                options.GlobalTags.Add("tag1", "value1");
                options.DefaultContextLabel = "test";
            }

            // Act
            var metrics = new MetricsBuilder().Configuration.Configure(SetupAction).Build();

            // Assert
            metrics.Options.DefaultContextLabel.Should().Be("test");
            metrics.Options.GlobalTags.Count.Should().Be(1);
            metrics.Options.GlobalTags.First().Key.Should().Be("tag1");
            metrics.Options.GlobalTags.First().Value.Should().Be("value1");
            metrics.Options.Enabled.Should().BeFalse();
        }
示例#15
0
        public static IWebHostBuilder CreateHostBuilder(string[] args)
        {
            Metrics = new MetricsBuilder()
                      //.Report.ToConsole()
                      .OutputMetrics.AsPrometheusPlainText()
                      .Configuration.Configure(p =>
            {
                p.DefaultContextLabel = "Application";
                p.GlobalTags.Add("app", "avia");
                p.Enabled          = true;
                p.ReportingEnabled = true;
            })
                      .Build();

            return
                (WebHost.CreateDefaultBuilder(args)
                 .ConfigureMetrics(Metrics)
                 .ConfigureHealth(
                     builder =>
            {
                builder.OutputHealth.AsPlainText();

                builder.HealthChecks.AddCheck("Database connect", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("Database Connection OK")));
                //builder.HealthChecks.AddHttpGetCheck("github", new Uri("https://github.com/"), TimeSpan.FromSeconds(1));

                builder.Report.Using(new MetricHealthReporter(Metrics)
                {
                    ReportInterval = TimeSpan.FromSeconds(5)
                });
            })
                 .UseHealth()
                 .UseMetrics(
                     options =>
            {
                options.EndpointOptions = endpointsOptions =>
                {
                    endpointsOptions.MetricsTextEndpointOutputFormatter = Metrics.OutputMetricsFormatters.First(p => p is MetricsPrometheusTextOutputFormatter);
                };
            })
                 .UseStartup <Startup>());
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var metrics = new MetricsBuilder()
                          .Report.ToInfluxDb(options =>
            {
                options.InfluxDb.BaseUri  = new Uri("http://influxdb:8086");
                options.InfluxDb.Database = "appmetrics";
                options.InfluxDb.UserName = "******";
                options.InfluxDb.Password = "******";
            })
                          .Build();

            var health = AppMetricsHealth.CreateDefaultBuilder().Configuration.Configure(new HealthOptions()
            {
                Enabled = true, ApplicationName = "http://health.local.com", ReportingEnabled = true
            })
                         .Report.ToMetrics(metrics)
                         .HealthChecks.AddSqlCachedCheck("Teste de conexão com o banco.", () => new MySql.Data.MySqlClient.MySqlConnection("Server=mysql;Database=healthcheck;Uid=healthcheckuser;Pwd=healthcheckpws;SslMode=none;"),
                                                         TimeSpan.FromSeconds(10),
                                                         TimeSpan.FromMinutes(1))
                         .HealthChecks.AddPingCheck("Google Ping", "google.com", TimeSpan.FromSeconds(10))
                         .HealthChecks.AddHttpGetCheck("GitHub", new Uri("https://github.com"), TimeSpan.FromSeconds(10))
                         .BuildAndAddTo(services);

            services.AddHealth(health);
            services.AddHealthEndpoints();

            services.AddMetrics(metrics);

            // ASP.NET CORE 2.1
            // Metricas
            services.AddMetricsReportingHostedService();
            // Healthcheck
            services.AddHealthReportingHostedService();

            services.AddMetricsTrackingMiddleware();

            services.AddMvc().AddMetrics();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
示例#17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var metrics = new MetricsBuilder()
                          .Configuration.Configure(
                options =>
            {
                options.AddServerTag();
                options.AddEnvTag();
                options.AddAppTag("BP4");
            })
                          .OutputMetrics.AsPrometheusPlainText()
                          .Build();

            services.AddMetrics(metrics);
            services.AddMetricsReportingHostedService();
            services.AddMetricsEndpoints();
            services.AddMetricsTrackingMiddleware();
            services.AddMvcCore().AddMetricsCore();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        public void Can_use_console_reporter_with_setup_action_to_override_defaults()
        {
            // Arrange
            var filter  = new MetricsFilter().WhereType(MetricType.Apdex);
            var builder = new MetricsBuilder().Report.ToConsole(
                options =>
            {
                options.MetricsOutputFormatter = new TestMetricsFormatter();
                options.Filter        = filter;
                options.FlushInterval = TimeSpan.FromDays(1);
            });

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.Should().Contain(reportMetrics => reportMetrics is ConsoleMetricsReporter);
            metrics.Reporters.First().FlushInterval.Should().Be(TimeSpan.FromDays(1));
            metrics.Reporters.First().Filter.Should().BeSameAs(filter);
            metrics.Reporters.First().Formatter.Should().BeOfType <TestMetricsFormatter>();
        }
示例#19
0
        public void When_using_http_reporter_with_setup_action_flush_interval_less_than_zero_should_throw()
        {
            // Arrange
            Action action = () =>
            {
                // Act
                var uri           = "http://localhost/metrics";
                var flushInterval = TimeSpan.FromSeconds(-1);
                var builder       = new MetricsBuilder().Report.OverHttp(
                    options =>
                {
                    options.HttpSettings.RequestUri = new Uri(uri);
                    options.FlushInterval           = flushInterval;
                });

                var unused = builder.Build();
            };

            // Assert
            action.Should().Throw <InvalidOperationException>();
        }
示例#20
0
        private static IMetricsRoot InitAppMetrics()
        {
            var metrics = new MetricsBuilder()
                          .Configuration.Configure(options =>
            {
                options.DefaultContextLabel = "MVC";
                options.AddAppTag(Assembly.GetExecutingAssembly().GetName().Name);
                options.AddServerTag(Environment.MachineName);

#if DEBUG
                options.AddEnvTag("Dev");
#else
                options.AddEnvTag("Release");
#endif

                options.GlobalTags.Add("my_custom_tag", "MyCustomValue");
            })
                          .Build();

            return(metrics);
        }
            /// <summary>
            ///     Builds a <see cref="WavefrontAspNetCoreReporter"/>.
            /// </summary>
            /// <returns>The <see cref="WavefrontAspNetCoreReporter"/> instance.</returns>
            /// <param name="wavefrontSender">
            ///     The Wavefront sender instance that handles the sending of data to Wavefront,
            ///     via either Wavefront proxy or direct ingestion.
            /// </param>
            public WavefrontAspNetCoreReporter Build(IWavefrontSender wavefrontSender)
            {
                source = string.IsNullOrWhiteSpace(source) ? Utils.GetDefaultSource() : source;

                var globalTags = new Dictionary <string, string>
                {
                    { ApplicationTagKey, applicationTags.Application }
                };

                if (applicationTags.CustomTags != null)
                {
                    foreach (var customTag in applicationTags.CustomTags)
                    {
                        if (!globalTags.ContainsKey(customTag.Key))
                        {
                            globalTags.Add(customTag.Key, customTag.Value);
                        }
                    }
                }

                var metrics = new MetricsBuilder()
                              .Configuration.Configure(
                    options =>
                {
                    options.DefaultContextLabel = AspNetCoreContext;
                    options.GlobalTags          = new GlobalMetricTags(globalTags);
                })
                              .Report.ToWavefront(
                    options =>
                {
                    options.WavefrontSender = wavefrontSender;
                    options.Source          = source;
                    options.WavefrontHistogram.ReportMinuteDistribution = true;
                    options.FlushInterval = TimeSpan.FromSeconds(reportingIntervalSeconds);
                })
                              .Build();

                return(new WavefrontAspNetCoreReporter(
                           metrics, wavefrontSender, applicationTags, source));
            }
        public void When_using_socket_reporter_with_setup_actions_flush_interval_less_than_zero_should_throw()
        {
            // Arrange
            Action action = () =>
            {
                // Act
                var flushInterval = TimeSpan.FromSeconds(-1);
                var settings      = new SocketSettings(defaultProtocol, defaultAddress, defaultPort);
                var builder       = new MetricsBuilder().Report.OverTcp(
                    options =>
                {
                    options.FlushInterval          = flushInterval;
                    options.MetricsOutputFormatter = new TestMetricsFormatter();
                    options.SocketSettings         = settings;
                });

                var unused = builder.Build();
            };

            // Assert
            action.Should().Throw <InvalidOperationException>();
        }
示例#23
0
        public void Can_bind_metrics_options_from_configuration()
        {
            // Arrange
            var builder       = new MetricsBuilder();
            var keyValuePairs = new Dictionary <string, string>
            {
                { "MetricsOptions:DefaultContextLabel", "Testing" },
                { "MetricsOptions:GlobalTags:tag1", "value1" },
                { "MetricsOptions:GlobalTags:tag2", "value2" },
                { "MetricsOptions:Enabled", "false" }
            };
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(keyValuePairs).Build();

            // Act
            builder.Configuration.ReadFrom(configuration);
            var metrics = builder.Build();

            // Assert
            metrics.Options.DefaultContextLabel.Should().Be("Testing");
            metrics.Options.Enabled.Should().BeFalse();
            metrics.Options.GlobalTags.Count.Should().Be(2);
        }
示例#24
0
        private static IMetricsRoot InitAppMetrics(InitAppMetricsModel initAppMetricsModel)
        {
            GlobalMetricTags globalMetricTags = new GlobalMetricTags();

            if (initAppMetricsModel.GlobalTags != null)
            {
                foreach (var item in initAppMetricsModel.GlobalTags)
                {
                    globalMetricTags.Add(item.Key, item.Value);
                }
            }

            var metrics = new MetricsBuilder()
                          .Configuration.Configure(options =>
            {
                options.DefaultContextLabel = initAppMetricsModel.DefaultContextLabel;
                options.AddAppTag(Assembly.GetExecutingAssembly().GetName().Name);
                options.AddServerTag(Environment.MachineName);
                options.AddEnvTag(initAppMetricsModel.EnvTag);
                options.GlobalTags = globalMetricTags;
            })
                          .Report.ToInfluxDb(options =>
            {
                options.InfluxDb.BaseUri                 = new Uri(initAppMetricsModel.BaseUri);
                options.InfluxDb.Database                = initAppMetricsModel.Database;
                options.InfluxDb.UserName                = initAppMetricsModel.UserName;
                options.InfluxDb.Password                = initAppMetricsModel.Password;
                options.HttpPolicy.BackoffPeriod         = TimeSpan.FromSeconds(30);
                options.HttpPolicy.FailuresBeforeBackoff = 5;
                options.HttpPolicy.Timeout               = TimeSpan.FromSeconds(3);
                options.FlushInterval = TimeSpan.FromSeconds(5);

                options.InfluxDb.CreateDataBaseIfNotExists = true;                //如果没有库,则创建
                options.MetricsOutputFormatter             = new MetricsInfluxDbLineProtocolOutputFormatter();
            })
                          .Build();

            return(metrics);
        }
示例#25
0
        public void Should_merge_global_tags_when_key_values_provided_that_match_an_existing_tag()
        {
            // Arrange
            var keyValuePairs = new Dictionary <string, string>
            {
                { "MetricsOptions:GlobalTags:tag1", "replaced" },
                { "MetricsOptions:GlobalTags:tag2", "added" }
            };
            var options = new MetricsOptions();

            options.GlobalTags.Add("tag1", "value1");

            // Act
            var metrics = new MetricsBuilder().Configuration.Configure(options, keyValuePairs).Build();

            // Assert
            metrics.Options.GlobalTags.Count.Should().Be(2);
            metrics.Options.GlobalTags.First().Key.Should().Be("tag1");
            metrics.Options.GlobalTags.First().Value.Should().Be("replaced");
            metrics.Options.GlobalTags.Skip(1).First().Key.Should().Be("tag2");
            metrics.Options.GlobalTags.Skip(1).First().Value.Should().Be("added");
        }
        public static IServiceCollection ConfigureMetrics(
            this IServiceCollection services,
            HostBuilderContext hostContext,
            bool filterMetricValueTypes)
        {
            var metricsConfigSection = hostContext.Configuration.GetSection(nameof(MetricsOptions));
            // Metrics = AppMetrics.CreateDefaultBuilder() to use the default configuration

            var metrics = new MetricsBuilder()
                          .Configuration.Configure(options =>
            {
                options.AddServerTag();
                options.AddAppTag();
                options.AddEnvTag();
            })
                          .Configuration.Configure(metricsConfigSection.AsEnumerable())
                          .MetricFields.Configure(
                fields =>
            {
                if (filterMetricValueTypes)
                {
                    fields.Counter.Set(CounterFields.Value, "val");
                    fields.Gauge.Set(GaugeFields.Value, "val");
                    fields.Counter.Exclude(CounterFields.Total, CounterFields.SetItem, CounterFields.SetItemPercent);
                    fields.Meter.OnlyInclude(MeterFields.Rate1M);
                    fields.Histogram.OnlyInclude(HistogramFields.P95, HistogramFields.P99);
                }
            })
                          .OutputEnvInfo.AsPlainText()
                          .OutputMetrics.AsPlainText()
                          .SampleWith.ForwardDecaying(TimeSpan.FromMinutes(30)).TimeWith.Clock(new TestClock())
                          .Report.Using <SimpleConsoleMetricsReporter>(TimeSpan.FromSeconds(2))
                          .Build();

            services.AddSingleton(metrics);

            return(services);
        }
示例#27
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("ooooooooooooooooooooooooooooooooooooooooooooooo");
            Console.WriteLine(" S T A R T I N G");
            Console.WriteLine("ooooooooooooooooooooooooooooooooooooooooooooooo");

            var metrics = new MetricsBuilder()
                          .Report.ToElasticsearch(_elasticUri, _elasticIndex)
                          .Report.ToConsole()
                          .Build();

            Track.Init(metrics);

            Track.StartReporter(TimeSpan.FromSeconds(1));
            await RunProducerConsumer().ConfigureAwait(false);

            await Track.FlushReporter().ConfigureAwait(false);

            Console.WriteLine("ooooooooooooooooooooooooooooooooooooooooooooooo");
            Console.WriteLine(" S T O P P E D - Press any key");
            Console.WriteLine("ooooooooooooooooooooooooooooooooooooooooooooooo");
            System.Console.ReadKey();
        }
        public void Can_use_udp_socket_reporter_with_options()
        {
            // Arrange
            var filter        = new MetricsFilter().WhereType(MetricType.Apdex);
            var flushInterval = TimeSpan.FromDays(1);
            var settings      = new SocketSettings(defaultProtocol, defaultAddress, defaultPort);
            var options       = new MetricsReportingSocketOptions();

            options.Filter                 = filter;
            options.FlushInterval          = flushInterval;
            options.MetricsOutputFormatter = new TestMetricsFormatter();
            options.SocketSettings         = settings;
            var builder = new MetricsBuilder().Report.OverUdp(options);

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.Should().Contain(reportMetrics => reportMetrics is SocketMetricsReporter);
            metrics.Reporters.First().FlushInterval.Should().Be(flushInterval);
            metrics.Reporters.First().Filter.Should().BeSameAs(filter);
            metrics.Reporters.First().Formatter.Should().BeOfType <TestMetricsFormatter>();
        }
示例#29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            var metrics = new MetricsBuilder()
                          .Configuration.Configure(
                options =>
            {
                options.AddServerTag();
                options.AddEnvTag();
                options.AddAppTag();
            })
                          .OutputMetrics.AsPrometheusPlainText()
                          .Build();

            services.AddMetrics(metrics);

            var health = AppMetricsHealth.CreateDefaultBuilder().Report.ToMetrics(metrics).BuildAndAddTo(services);

            services.AddMetricsReportingHostedService();
            services.AddHealthReportingHostedService();

            services.AddHealth(health);

            services.AddMetricsEndpoints();
            services.AddHealthEndpoints();
            services.AddMetricsTrackingMiddleware();
            services.AddMvc().AddMetrics();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
示例#30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var metrics = new MetricsBuilder()
                          .Configuration.Configure(
                options =>
            {
                options.AddServerTag();
                options.AddEnvTag();
                options.AddAppTag();
            })
                          .OutputMetrics.AsPrometheusPlainText()
                          .Build();

            services.AddMetrics(metrics);

            var health = AppMetricsHealth.CreateDefaultBuilder()//.Configuration.Configure(new HealthOptions() { Enabled = true, ApplicationName = "http://health.local.com", ReportingEnabled = true })
                         .Report.ToMetrics(metrics)
                         .HealthChecks.AddSqlCachedCheck("Teste de conexão com o banco.", () => new MySql.Data.MySqlClient.MySqlConnection("Server=mysql;Database=healthcheck;Uid=healthcheckuser;Pwd=healthcheckpws;SslMode=none;"),
                                                         TimeSpan.FromSeconds(10),
                                                         TimeSpan.FromMinutes(1))
                         .HealthChecks.AddPingCheck("Google Ping", "google.com", TimeSpan.FromSeconds(10))
                         .HealthChecks.AddHttpGetCheck("GitHub", new Uri("https://github.com"), TimeSpan.FromSeconds(10))
                         .HealthChecks.RegisterFromAssembly(services)
                         .BuildAndAddTo(services);

            services.AddMetricsReportingHostedService();
            services.AddHealthReportingHostedService();

            services.AddHealth(health);

            services.AddMetricsEndpoints();
            services.AddHealthEndpoints();
            services.AddMetricsTrackingMiddleware();
            services.AddMvc().AddMetrics();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }