private readonly ConcurrentDictionary <EventChangeEventArgs, bool> _eventUpdates; // boolean value indicating if this is fixture update

        public EventChangeManager(TimeSpan fixtureChangeInterval,
                                  TimeSpan resultChangeInterval,
                                  ISportDataProvider sportDataProvider,
                                  ISportEventCache sportEventCache,
                                  IOddsFeedConfiguration config,
                                  IMetricsRoot metricsRoot)
        {
            Guard.Argument(config, nameof(config)).NotNull();
            Guard.Argument(sportDataProvider, nameof(sportDataProvider)).NotNull();
            Guard.Argument(sportEventCache, nameof(sportEventCache)).NotNull();

            _config            = config;
            _sportDataProvider = (SportDataProvider)sportDataProvider;
            _sportEventCache   = sportEventCache;
            _metricsRoot       = metricsRoot;

            LastFixtureChange     = DateTime.MinValue;
            LastResultChange      = DateTime.MinValue;
            FixtureChangeInterval = fixtureChangeInterval >= TimeSpan.FromMinutes(1) ? fixtureChangeInterval : TimeSpan.FromHours(1);
            ResultChangeInterval  = resultChangeInterval >= TimeSpan.FromMinutes(1) ? resultChangeInterval : TimeSpan.FromHours(1);
            IsRunning             = false;

            _fixtureTimer          = new SdkTimer(TimeSpan.FromSeconds(1), fixtureChangeInterval);
            _resultTimer           = new SdkTimer(TimeSpan.FromSeconds(1), ResultChangeInterval);
            _fixtureTimer.Elapsed += FixtureTimerOnElapsed;
            _resultTimer.Elapsed  += ResultTimerOnElapsed;

            _eventUpdates = new ConcurrentDictionary <EventChangeEventArgs, bool>();

            _isDispatching = false;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MarketDescriptionCache"/> class
        /// </summary>
        /// <param name="cache">A <see cref="ObjectCache"/> used to store market descriptors</param>
        /// <param name="dataProvider">A <see cref="IDataProvider{T}"/> used to fetch market descriptors</param>
        /// <param name="prefetchLanguages">A <see cref="IReadOnlyCollection{CultureInfo}"/> specifying the languages for which the data should be pre-fetched</param>
        /// <param name="accessToken">The <see cref="ISdkConfigurationSection.AccessToken"/> used to access UF REST API</param>
        /// <param name="fetchInterval">The fetch interval</param>
        /// <param name="cacheItemPolicy">The cache item policy</param>
        /// <param name="metrics">A <see cref="IMetricsRoot"/> used to record sdk metrics</param>
        public MarketDescriptionCache(ObjectCache cache,
                                      IDataProvider <IEnumerable <MarketDescriptionDTO> > dataProvider,
                                      IEnumerable <CultureInfo> prefetchLanguages,
                                      string accessToken,
                                      TimeSpan fetchInterval,
                                      CacheItemPolicy cacheItemPolicy,
                                      IMetricsRoot metrics = null)
        {
            Guard.Argument(cache, nameof(cache)).NotNull();
            Guard.Argument(dataProvider, nameof(dataProvider)).NotNull();
            var cultureInfos = prefetchLanguages?.ToList();

            Guard.Argument(cultureInfos, nameof(cultureInfos)).NotNull().NotEmpty();
            Guard.Argument(fetchInterval, nameof(fetchInterval)).Require(fetchInterval != null);

            _fetchInterval     = fetchInterval;
            _cacheItemPolicy   = cacheItemPolicy;
            TimeOfLastFetch    = DateTime.MinValue;
            Cache              = cache;
            _dataProvider      = dataProvider;
            _prefetchLanguages = new ReadOnlyCollection <CultureInfo>(cultureInfos ?? throw new InvalidOperationException());

            _tokenProvided = !string.IsNullOrEmpty(accessToken);
            var isProvided = _tokenProvided ? string.Empty : " not";

            _metrics = metrics ?? SdkMetricsFactory.MetricsRoot;

            ExecutionLog.LogDebug($"AccessToken for API is{isProvided} provided. It is required only when creating selections for UF markets via method ISelectionBuilder.SetIdUof(). There is no need for it when legacy feeds are used.");
        }
示例#3
0
        public static IWebHost BuildWebHost(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json").Build();

            Metrics = AppMetrics.CreateDefaultBuilder()
                      .OutputMetrics.AsPrometheusPlainText()
                      .OutputMetrics.AsPrometheusProtobuf()
                      .Configuration.ReadFrom(configuration)
                      .Build();

            return(WebHost.CreateDefaultBuilder(args)
                   .ConfigureMetrics(Metrics)
                   .UseMetrics(
                       options =>
            {
                options.EndpointOptions = endpointsOptions =>
                {
                    endpointsOptions.MetricsTextEndpointOutputFormatter = new MetricsPrometheusTextOutputFormatter(new MetricsPrometheusOptions());
                    endpointsOptions.MetricsEndpointOutputFormatter = new MetricsPrometheusProtobufOutputFormatter(new MetricsPrometheusOptions());
                };
            })
                   .UseMetricsWebTracking()
                   .UseStartup <Startup>()
                   .UseUrls("http://localhost:10010/")
                   .Build());
        }
示例#4
0
        /// <summary>
        /// Metoda specialne pro WPF aplikace, ktere nepotrebuji zadny runner, ale hodi se logovani, metriky a konfigurace
        /// </summary>
        /// <returns></returns>
        public ServiceCollection Build()
        {
            var services = new ServiceCollection();

            // configuration
            var config = DefaultConfiguration.Create(configPaths.ToArray(), args);

            DefaultConfiguration.Configure(services, config);

            // app context
            var name    = config.GetValue <string>("app:name", null);
            var env     = config.GetValue <string>("app:env", null);
            var appInfo = new AppInfo(args, name, env);

            services.AddSingleton(appInfo);

            // logging
            var logsOptions = LogsOptions.Create(config, appInfo.Name);

            var(loggerFactory, defaultLogger) = DefaultLogging.Create(logsOptions, appInfo);
            DefaultLogging.ConfigureServices(services, loggerFactory, defaultLogger);

            // metrics
            var          metricsOptions = Conventions.MetricsOptions.Create(config);
            IMetricsRoot metrics        = DefaultMetrics.Create(metricsOptions, appInfo);

            DefaultMetrics.ConfigureServices(services, metrics, metricsOptions);

            // log few details about so far configured services for debugging purposes
            defaultLogger.Debug("StartUp: application {appInfo}", appInfo);
            defaultLogger.Debug("StartUp: logging {options}", logsOptions);
            defaultLogger.Debug("StartUp: metrics {options}", metricsOptions);

            return(services);
        }
示例#5
0
        public static IWebHost BuildWebHost(string[] args)
        {
            Metrics = AppMetrics.CreateDefaultBuilder()
                      .OutputMetrics.AsPrometheusPlainText()
                      .OutputMetrics.AsPrometheusProtobuf()
                      .Configuration.Configure(opt => {
                opt.AddAppTag("app-tag");
                opt.AddEnvTag("env-tag");
            })
                      .Build();

            return(WebHost.CreateDefaultBuilder(args)
                   .ConfigureMetrics(Metrics)
                   .UseMetrics(
                       options =>
            {
                options.EndpointOptions = endpointsOptions =>
                {
                    endpointsOptions.MetricsTextEndpointOutputFormatter = Metrics.OutputMetricsFormatters.GetType <MetricsPrometheusTextOutputFormatter>();
                    endpointsOptions.MetricsEndpointOutputFormatter = Metrics.OutputMetricsFormatters.GetType <MetricsPrometheusProtobufOutputFormatter>();
                };
            })
                   .UseUrls("http://*:5000")
                   .UseStartup <Startup>()
                   .Build());
        }
示例#6
0
        static void Main(string[] args)
        {
            Metrics = AppMetrics.CreateDefaultBuilder()
                      .OutputMetrics.AsPrometheusPlainText()
                      .Build();

            // Kestrel
            var builder = new WebHostBuilder()
                          .SuppressStatusMessages(true)
                          .UseKestrel(c => c.AddServerHeader = false)
                          //.UseEnvironment("Staging")
                          .ConfigureMetrics(Metrics)
                          .UseMetrics(
                options =>
            {
                options.EndpointOptions = endpointsOptions =>
                {
                    endpointsOptions.MetricsTextEndpointOutputFormatter =
                        Metrics.OutputMetricsFormatters.GetType <MetricsPrometheusTextOutputFormatter>();
                };
            })
                          .UseMetricsWebTracking()
                          .UseUrls("http://0.0.0.0:5000")
                          .ConfigureLogging((context, logging) => {
                logging.ClearProviders();
                logging.AddConsole();
            })
                          .UseStartup <StartUp>();
            var host = builder.Build();

            host.Run();
        }
示例#7
0
        protected GenomeFactoryBase(IEnumerable <TGenome> seeds = null)
        {
            Metrics        = new MetricsBuilder().Build();
            MetricsCounter = new CounterCollection(Metrics);

            InjectSeeds(seeds);
        }
示例#8
0
        public static void Main(string[] args)
        {
            Metrics = AppMetrics.CreateDefaultBuilder()
                      .OutputMetrics.AsPrometheusPlainText()
                      // .OutputMetrics.AsPrometheusProtobuf()
                      .Build();


            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService <DbzMySqlContext>();
                    DbzInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    //var logger = services.GetRequiredService<ILogger<Program>>();
                    Console.WriteLine("An error occurred while seeding the database.");
                    Console.WriteLine(ex.Message);
                }
            }


            host.Run();
        }
示例#9
0
        private static async Task WriteMetricsAsync(IMetricsRoot metrics, CancellationTokenSource cancellationTokenSource)
        {
            foreach (var unused in Enumerable.Range(0, 10))
            {
                RecordMetrics(metrics);
            }

            var metricsData = metrics.Snapshot.Get();

            WriteLine("Metrics Formatters");
            WriteLine("-------------------------------------------");

            foreach (var formatter in metrics.OutputMetricsFormatters)
            {
                WriteLine($"Formatter: {formatter.GetType().FullName}");
                WriteLine("-------------------------------------------");

                using (var stream = new MemoryStream())
                {
                    await formatter.WriteAsync(stream, metricsData, cancellationTokenSource.Token);

                    var result = Encoding.UTF8.GetString(stream.ToArray());

                    WriteLine(result);
                }
            }
        }
示例#10
0
 public AppMetricBehavior(IMetricsRoot metrics)
 {
     _metrics       = metrics;
     _requestMetric = new MeterOptions()
     {
         Name            = "Mediator Requests",
         MeasurementUnit = App.Metrics.Unit.Requests,
         RateUnit        = TimeUnit.Seconds,
         Context         = "application"
     };
     _exeTimer = new TimerOptions()
     {
         Name            = "Mediator Requests Execution Time",
         MeasurementUnit = App.Metrics.Unit.Requests,
         DurationUnit    = TimeUnit.Milliseconds,
         RateUnit        = TimeUnit.Seconds,
         Context         = "application"
     };
     _exception = new MeterOptions()
     {
         Name            = "Mediator Requests Exceptions",
         MeasurementUnit = App.Metrics.Unit.Requests,
         RateUnit        = TimeUnit.Seconds,
         Context         = "application"
     };
 }
        public static SillycoreAppBuilder WithAppMetrics(this SillycoreAppBuilder builder)
        {
            IMetricsRoot metrics = App.Metrics.AppMetrics.CreateDefaultBuilder()
                                   .OutputMetrics.AsPrometheusPlainText()
                                   .OutputMetrics.AsPlainText()
                                   .Build();


            builder.Services.AddMetrics();
            builder.BeforeBuild(() =>
            {
                IWebHostBuilder webhostBuilder = builder.DataStore
                                                 .Get <IWebHostBuilder>(Web.Constants.WebHostBuilder)
                                                 .ConfigureMetrics(metrics)
                                                 .UseMetrics(
                    options =>
                {
                    options.EndpointOptions = endpointsOptions =>
                    {
                        endpointsOptions.MetricsTextEndpointOutputFormatter = metrics.OutputMetricsFormatters.GetType <MetricsTextOutputFormatter>();
                        endpointsOptions.MetricsEndpointOutputFormatter     = metrics.OutputMetricsFormatters.GetType <MetricsPrometheusTextOutputFormatter>();
                    };
                });

                builder.DataStore.Set(Web.Constants.WebHostBuilder, webhostBuilder);
            });

            return(builder);
        }
示例#12
0
        public static IWebHost BuildWebHost(string[] args)
        {
            ConfigureLogging();

            Metrics = AppMetrics.CreateDefaultBuilder()
                      .OutputMetrics.AsPrometheusPlainText()
                      .OutputMetrics.AsPrometheusProtobuf()
                      .Build();

            return(WebHost.CreateDefaultBuilder(args)
                   .ConfigureMetrics(Metrics)
                   .UseMetrics(
                       options =>
            {
                options.EndpointOptions = endpointsOptions =>
                {
                    endpointsOptions.MetricsTextEndpointOutputFormatter = Metrics.OutputMetricsFormatters.GetType <MetricsPrometheusTextOutputFormatter>();
                    endpointsOptions.MetricsEndpointOutputFormatter = Metrics.OutputMetricsFormatters.GetType <MetricsPrometheusProtobufOutputFormatter>();
                };
            })
                   .UseSerilog()
                   .UseStartup <Startup>()
                   .UseUrls("http://localhost:1111")
                   .Build());
        }
 public TimedHostedService(ILogger logger, IModel channel, IMetricsRoot metrics)
 {
     _logger       = logger;
     _channel      = channel;
     _metrics      = metrics;
     CurrentStatus = Status.Stopped;
 }
示例#14
0
        private static IHostBuilder createHostBuilderWithPrometheus(string[] args)
        {
            IMetricsRoot metrics = AppMetrics
                                   .CreateDefaultBuilder()
                                   .OutputMetrics.AsPrometheusPlainText()
                                   .OutputMetrics.AsPrometheusProtobuf()
                                   .Build();

            // http://localhost:5000/metrics-text
            // http://localhost:5000/metrics

            return(Host
                   .CreateDefaultBuilder(args)
                   .ConfigureMetrics(metrics)
                   .UseMetricsWebTracking()
                   .UseMetrics(options =>
            {
                options.EndpointOptions = endpointsOptions =>
                {
                    endpointsOptions.MetricsTextEndpointOutputFormatter
                        = metrics.OutputMetricsFormatters.GetType <MetricsPrometheusTextOutputFormatter>();
                    //endpointsOptions.MetricsEndpointOutputFormatter
                    //  = metrics.OutputMetricsFormatters.GetType<MetricsPrometheusProtobufOutputFormatter>();
                };
            })
                   .ConfigureWebHostDefaults(webHostBuilder => webHostBuilder.UseStartup <Startup>()));
        }
        private static void Init()
        {
            var cfg = new ConfigurationBuilder()
                      .SetBasePath(AppContext.BaseDirectory)
                      .AddJsonFile("appsettings.json", optional: false)
                      .Build();

            var logFile = ResolveLogFilePath(cfg);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.Async(x => x.File(logFile))
                         .CreateLogger();
            Logger = Log.Logger.ForContext(typeof(Program));

            var metricsOptions     = cfg.GetSection("metrics").Get <MetricsOptions>();
            var instrumentationKey = ResolveInstrumentationKey(cfg);

            metrics = new MetricsBuilder()
                      .Configuration.Configure(metricsOptions)
                      .Report.ToApplicationInsights(opts =>
            {
                opts.InstrumentationKey      = instrumentationKey;
                opts.ItemsAsCustomDimensions = true;
            })
                      .Build();

            reporter = metrics.ReportRunner;
        }
        /*
         * Initializing metrics
         */

        #region Methods
        private static void InitializeMetrics()
        {
            //Building the metrics object and setting host and port
            Metrics = AppMetrics.CreateDefaultBuilder()
                      .Report.ToInfluxDb(options =>
            {
                options.InfluxDb.BaseUri  = new Uri("http://127.0.0.1:8086/");
                options.InfluxDb.Database = "sample-db";
                options.InfluxDb.CreateDataBaseIfNotExists = true;
            })
                      .Configuration.Configure(options =>
            {
                options.AddServerTag();
            })
                      .Build();

            //Start logging metrics
            var scheduler = new AppMetricsTaskScheduler(
                TimeSpan.FromSeconds(5),
                async() =>
            {
                await Task.WhenAll(Metrics.ReportRunner.RunAllAsync());
            });

            scheduler.Start();

            machineMetricsThread.Start();
        }
示例#17
0
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            Metrics = new MetricsBuilder()
                      .OutputMetrics.AsPrometheusPlainText()
                      .Configuration.Configure(p =>
            {
                p.DefaultContextLabel = "Application";
                p.GlobalTags.Add("app", "TextBooker.Api");
                p.Enabled          = true;
                p.ReportingEnabled = true;
            })
                      .Build();

            return(Host
                   .CreateDefaultBuilder(args)
                   .ConfigureMetrics(Metrics)
                   .UseMetrics(
                       options =>
            {
                options.EndpointOptions = endpointsOptions =>
                {
                    endpointsOptions.MetricsTextEndpointOutputFormatter = Metrics.OutputMetricsFormatters.First(p => p is MetricsPrometheusTextOutputFormatter);
                };
            })
                   .ConfigureWebHostDefaults(builder =>
            {
                builder.UseStartup <Startup>();
            }));
        }
示例#18
0
        static void Init()
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", false)
                                .Build();

            var logFile = configuration.GetValue("logFile", "ApplicationInsightsSandbox.log");

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.Async(x => x.File(logFile))
                         .CreateLogger();

            Logger = Log.Logger.ForContext(typeof(Program));

            // read configuration
            var metricsOptions     = configuration.GetSection("metrics").Get <MetricsOptions>();
            var instrumentationKey = GetAppInsightsInstrumentationKey(configuration);

            metrics = new MetricsBuilder()
                      .Configuration.Configure(metricsOptions)
                      .Report.ToApplicationInsights(instrumentationKey)
                      .Build();

            reporter = metrics.ReportRunner;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Feed"/> class
        /// </summary>
        /// <param name="config">A <see cref="IOddsFeedConfiguration"/> instance representing feed configuration</param>
        /// <param name="isReplay">Value indicating whether the constructed instance will be used to connect to replay server</param>
        /// <param name="loggerFactory">A <see cref="ILoggerFactory"/> used to create <see cref="ILogger"/> used within sdk</param>
        /// <param name="metricsRoot">A <see cref="IMetricsRoot"/> used to provide metrics within sdk</param>
        protected Feed(IOddsFeedConfiguration config, bool isReplay, ILoggerFactory loggerFactory = null, IMetricsRoot metricsRoot = null)
        {
            Guard.Argument(config, nameof(config)).NotNull();

            FeedInitialized = false;

            UnityContainer = new UnityContainer();
            //UnityContainer = new UnityContainer().EnableDiagnostic();
            UnityContainer.RegisterBaseTypes(config, loggerFactory, metricsRoot);
            InternalConfig = UnityContainer.Resolve <IOddsFeedConfigurationInternal>();
            if (isReplay || InternalConfig.Environment == SdkEnvironment.Replay)
            {
                InternalConfig.EnableReplayServer();
            }

            _log = SdkLoggerFactory.GetLoggerForExecution(typeof(Feed));

            LogInit();

            _metricsRoot          = UnityContainer.Resolve <IMetricsRoot>();
            _metricsLogger        = SdkLoggerFactory.GetLoggerForStats(typeof(Feed));
            _metricsTaskScheduler = new AppMetricsTaskScheduler(
                TimeSpan.FromSeconds(InternalConfig.StatisticsTimeout),
                async() => { await LogMetricsAsync(); });
        }
示例#20
0
 public MetricsRegistry(IMetricsRoot metricsRoot, IConfiguration configuration)
 {
     this.metricsRoot = metricsRoot;
     this.findQueries = new CounterOptions {
         Name = configuration["app:name"]
     };
 }
示例#21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddHealthChecks();

            services.AddOpenTracing(x =>
            {
                x.ConfigureAspNetCore(options =>
                {
                    options.Hosting.IgnorePatterns.Add(ctx => ctx.IsHealthCheckEndpoint());
                    options.Hosting.IgnorePatterns.Add(ctx => ctx.IsMetricsEndpoint());
                });
            });
            services.AddJaeger(Configuration);

            Metrics = AppMetrics.CreateDefaultBuilder()
                      .OutputMetrics.AsPrometheusPlainText()
                      .Build();

            services.AddMetrics(Metrics);
            services.AddMetricsEndpoints(x =>
            {
                x.MetricsEndpointEnabled         = false;
                x.EnvironmentInfoEndpointEnabled = false;

                x.MetricsTextEndpointOutputFormatter =
                    Metrics.OutputMetricsFormatters.OfType <MetricsPrometheusTextOutputFormatter>().First();
            });
        }
        public void Should_AllMetricsHaveValidValues_When_AllNodesAreUp()
        {
            _metricsRoot = new MetricsBuilder().Build();
            var cluster = GetNewTemporaryCluster(b =>
                                                 b.WithMetrics(
                                                     _metricsRoot.CreateDriverMetricsProvider(
                                                         new DriverAppMetricsOptions().SetRefreshIntervalMilliseconds(1000)),
                                                     new DriverMetricsOptions()
                                                     .SetEnabledNodeMetrics(NodeMetric.AllNodeMetrics)
                                                     .SetEnabledSessionMetrics(SessionMetric.AllSessionMetrics)));
            var session = cluster.Connect();

            Assert.AreEqual(25, NodeMetric.AllNodeMetrics.Count());
            Assert.AreEqual(25,
                            MetricsTests.Counters.Concat(MetricsTests.Gauges.Concat(MetricsTests.Timers.Concat(MetricsTests.Meters)))
                            .Union(NodeMetric.DefaultNodeMetrics).Count());
            Assert.AreEqual(1, MetricsTests.Timers.Length);
            Assert.IsTrue(NodeMetric.AllNodeMetrics.SequenceEqual(NodeMetric.AllNodeMetrics.Distinct()));
            Assert.AreEqual(5, SessionMetric.AllSessionMetrics.Count());

            foreach (var i in Enumerable.Range(0, 1000))
            {
                session.Execute("SELECT * FROM system.local");
            }

            var waitedForRefresh = false;
            var metrics          = session.GetMetrics();

            foreach (var h in cluster.AllHosts())
            {
                foreach (var c in MetricsTests.Counters)
                {
                    Assert.AreEqual(0, metrics.GetNodeCounter(h, c).GetValue());
                }

                Assert.AreEqual(2, MetricsTests.Gauges.Length);
                Assert.AreEqual(0, metrics.GetNodeGauge(h, NodeMetric.Gauges.InFlight).GetValue());

                if (!waitedForRefresh)
                {
                    waitedForRefresh = true;
                    TestHelper.RetryAssert(
                        () => { Assert.Greater(metrics.GetNodeGauge(h, NodeMetric.Gauges.OpenConnections).GetValue(), 0); },
                        200,
                        10);
                }

                Assert.Greater(metrics.GetNodeTimer(h, NodeMetric.Timers.CqlMessages).GetValue().Histogram.Max, 0);

                Assert.Greater(metrics.GetNodeMeter(h, NodeMetric.Meters.BytesSent).GetValue().Count, 0);
                Assert.Greater(metrics.GetNodeMeter(h, NodeMetric.Meters.BytesReceived).GetValue().Count, 0);
            }

            Assert.AreEqual(0, metrics.GetSessionCounter(SessionMetric.Counters.CqlClientTimeouts).GetValue());
            Assert.Greater(metrics.GetSessionTimer(SessionMetric.Timers.CqlRequests).GetValue().Histogram.Max, 0);
            Assert.Greater(metrics.GetSessionMeter(SessionMetric.Meters.BytesSent).GetValue().Count, 0);
            Assert.Greater(metrics.GetSessionMeter(SessionMetric.Meters.BytesReceived).GetValue().Count, 0);
            Assert.AreEqual(3, metrics.GetSessionGauge(SessionMetric.Gauges.ConnectedNodes).GetValue());
        }
示例#23
0
 public void Teardown()
 {
     if (_metricsRoot != null)
     {
         _metricsRoot.Manage.Disable();
         _metricsRoot = null;
     }
 }
示例#24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitMqMessageReceiver" /> class
        /// </summary>
        /// <param name="channel">A <see cref="IRabbitMqConsumerChannel" /> representing a consumer channel to the RabbitMQ broker</param>
        /// <param name="expectedResponseType">The type of the message receiver is expecting</param>
        public RabbitMqMessageReceiver(IRabbitMqConsumerChannel channel, TicketResponseType expectedResponseType)
        {
            Guard.Argument(channel, nameof(channel)).NotNull();

            _consumerChannel            = channel;
            _expectedTicketResponseType = expectedResponseType;
            _metrics = SdkMetricsFactory.MetricsRoot;
        }
 private WavefrontAspNetCoreReporter(IMetricsRoot metrics, IWavefrontSender wavefrontSender,
                                     ApplicationTags applicationTags, string source)
 {
     Metrics         = metrics;
     WavefrontSender = wavefrontSender;
     ApplicationTags = applicationTags;
     Source          = source;
 }
 /// <summary>
 /// This method must be called before using metrics, it accepts
 /// a full configured <see cref="MetricsBuilder"/> and is used
 /// to create an internal version of metrics to help you in
 /// creating metrics.
 /// </summary>
 /// <param name="builder"></param>
 public static void InitMetrics(IMetricsBuilder builder)
 {
     if (Metrics != null)
     {
         throw new JarvisFrameworkEngineException("Metrics already configured, cannot configure more than once");
     }
     Metrics = builder.Build();
 }
示例#27
0
        private static IWebHost BuildWebHost(string[] args)
        {
            Metrics = AppMetrics.CreateDefaultBuilder()
                      .OutputMetrics.AsPrometheusProtobuf()
                      .Build();
            var builder = new WebHostBuilder()
                          .UseKestrel(options => options.AddServerHeader = false)
                          .UseContentRoot(Directory.GetCurrentDirectory())
                          .UseMetrics(options => {
                options.EndpointOptions = endpointsOptions => {
                    endpointsOptions.MetricsTextEndpointEnabled     = false;
                    endpointsOptions.MetricsEndpointOutputFormatter = Metrics.OutputMetricsFormatters
                                                                      .GetType <MetricsPrometheusProtobufOutputFormatter>();
                };
            })
                          .ConfigureAppConfiguration((hostingContext, config) => {
                var hostingEnvironment = hostingContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", true, true).AddJsonFile(
                    string.Format("appsettings.{0}.json", hostingEnvironment.EnvironmentName), true, true);

                if (hostingEnvironment.IsDevelopment())
                {
                    var assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
                    if (assembly != null)
                    {
                        config.AddUserSecrets(assembly, true);
                    }
                }

                config.AddEnvironmentVariables();
                config.AddDockerSecrets(cfg => { cfg.Optional = true; });
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
                var jsonCfg = config.Build();
                if (!string.IsNullOrWhiteSpace(jsonCfg["ConsulOptions:ServiceName"]))
                {
                    config.AddConsul(jsonCfg["ConsulOptions:ServiceName"], ConsulConfigCancellationTokenSource.Token,
                                     opt => {
                        opt.ReloadOnChange             = true;
                        opt.Optional                   = true;
                        opt.ConsulConfigurationOptions = cfg => {
                            cfg.Address    = new Uri(jsonCfg["ConsulOptions:HttpEndpoint"]);
                            cfg.Datacenter = jsonCfg["ConsulOptions:Datacenter"];
                        };
                    }
                                     );
                }
                InitializeLogs(config.Build());
            })
                          .UseDefaultServiceProvider((ctx, opt) => { })
                          .UseHealthChecks("/hc")
                          .UseStartup <TStart>()
                          .UseSerilog();

            return(builder.Build());
        }
示例#28
0
 public Metrics(IMetricsRoot metrics)
 {
     _metrics = metrics;
     _counter = new CounterOptions {
         Name = "my_counter"
     };
     _metrics.Measure.Counter.Increment(_counter);
     _metrics.Measure.Counter.Decrement(_counter);
 }
示例#29
0
 public PopulationService(IMediator mediator, IEventStoreConnection connection, IMetricsRoot metrics,
                          IHostApplicationLifetime lifetime, ILogger <PopulationService> logger)
 {
     _mediator   = mediator;
     _connection = connection;
     _metrics    = metrics;
     _lifetime   = lifetime;
     _logger     = logger;
 }
示例#30
0
        public static IMetricsRoot GetMetrics()
        {
            if (_metrics == null)
            {
                _metrics = InitAppMetrics();
            }

            return(_metrics);
        }