예제 #1
0
 public SetDataPerformanceInstrumentation(IMetricsFactory metricsFactory)
 {
     this.setDataSuccess     = metricsFactory.Create0D("setDataSuccess");
     this.setDataFailure     = metricsFactory.Create0D("setDataFailure");
     this.setDataLatency     = metricsFactory.Create0D("setDataLatencyMs");
     this.setDataNodesLoaded = metricsFactory.Create0D("setDataNodesLoaded");
 }
예제 #2
0
        public void TestCounterMetrics()
        {
            const string    name    = "countertest";
            const string    desc    = "countertestdesc";
            IMetricsFactory factory = TangFactory.GetTang().NewInjector().GetInstance <IMetricsFactory>();

            var longCounter = factory.CreateCounter(name, desc, 5);

            Assert.Equal(name, longCounter.Info.Name);
            Assert.Equal(desc, longCounter.Info.Description);

            MetricTestUtils.RecordBuilderForTests recordBuilder = new MetricTestUtils.RecordBuilderForTests();
            SnapshotRequest request = new SnapshotRequest(recordBuilder, false);

            longCounter.OnNext(request);
            recordBuilder.Validate(name, 5);
            recordBuilder.Reset();

            longCounter.Increment();
            longCounter.OnNext(request);
            recordBuilder.Validate(name, 6);
            recordBuilder.Reset();

            longCounter.OnNext(request);
            Assert.False(recordBuilder.LongKeyPresent(name), "Metric is not supposed to be recorded.");

            request = new SnapshotRequest(recordBuilder, true);
            longCounter.OnNext(request);
            recordBuilder.Validate(name, 6);
            recordBuilder.Reset();
        }
예제 #3
0
 public DeletePerformanceInstrumentation(IMetricsFactory metricsFactory)
 {
     this.deleteSuccess   = metricsFactory.Create0D("deleteSuccess");
     this.deleteFailure   = metricsFactory.Create0D("deleteFailure");
     this.deleteLatencyMs = metricsFactory.Create0D("deleteLatencyMs");
     this.deleteNodeCount = metricsFactory.Create0D("deleteNodeCount");
 }
예제 #4
0
        private DefaultMetricsSourceImpl(
            [Parameter(typeof(DefaultMetricsSourceParameters.ContextOrTaskName))] string contextOrTaskName,
            [Parameter(typeof(DefaultMetricsSourceParameters.EvaluatorId))] string evaluatorId,
            [Parameter(typeof(DefaultMetricsSourceParameters.SourceContext))] string sourceContext,
            [Parameter(typeof(DefaultMetricsSourceParameters.RecordName))] string recordName,
            IMetricsFactory metricsFactory)
        {
            _contextOrTaskName = contextOrTaskName;
            _evaluatorId = evaluatorId;
            _sourceContext = sourceContext;
            _recordName = recordName;
            _metricsFactory = metricsFactory;

            _counters = new MutableMetricContainer<ICounter>(
                (name, desc) => metricsFactory.CreateCounter(name, desc),
                this);
            _longGauges = new MutableMetricContainer<ILongGauge>(
                (name, desc) => metricsFactory.CreateLongGauge(name, desc),
                this);
            _doubleGauges = new MutableMetricContainer<IDoubleGauge>(
                (name, desc) => metricsFactory.CreateDoubleGauge(name, desc),
                this);
            _rates = new MutableMetricContainer<IRate>(
                (name, desc) => metricsFactory.CreateRateMetric(name, desc),
                this);
        }
예제 #5
0
    public TypedConsumerService(
        ILogger <TypedConsumerService <TInput> > logger,
        IMetricsFactory <TypedConsumerService <TInput> >?metrics,
        IBackgroundTaskQueue <MotorCloudEvent <TInput> > queue,
        IMessageDeserializer <TInput> deserializer,
        IOptions <ContentEncodingOptions> encodingOptions,
        IEnumerable <IMessageDecoder> decoders,
        IMessageConsumer <TInput> consumer)
    {
        _logger       = logger;
        _queue        = queue;
        _deserializer = deserializer;
        _consumer     = consumer;
        _consumer.ConsumeCallbackAsync = SingleMessageConsumeAsync;
        _encodingOptions = encodingOptions.Value;

        _messageDeserialization =
            metrics?.CreateSummary("message_deserialization", "Message deserialization duration in ms");
        _messageDecoding =
            metrics?.CreateSummary("message_decoding", "Message decoding duration in ms");

        _decoderByEncoding = new Dictionary <string, IMessageDecoder>();
        foreach (var decoder in decoders)
        {
            _decoderByEncoding[decoder.Encoding] = decoder;
        }
    }
        private DefaultMetricsSourceImpl(
            [Parameter(typeof(DefaultMetricsSourceParameters.ContextOrTaskName))] string contextOrTaskName,
            [Parameter(typeof(DefaultMetricsSourceParameters.EvaluatorId))] string evaluatorId,
            [Parameter(typeof(DefaultMetricsSourceParameters.SourceContext))] string sourceContext,
            [Parameter(typeof(DefaultMetricsSourceParameters.RecordName))] string recordName,
            IMetricsFactory metricsFactory)
        {
            _contextOrTaskName = contextOrTaskName;
            _evaluatorId       = evaluatorId;
            _sourceContext     = sourceContext;
            _recordName        = recordName;
            _metricsFactory    = metricsFactory;

            _counters = new MutableMetricContainer <ICounter>(
                (name, desc) => metricsFactory.CreateCounter(name, desc),
                this);
            _longGauges = new MutableMetricContainer <ILongGauge>(
                (name, desc) => metricsFactory.CreateLongGauge(name, desc),
                this);
            _doubleGauges = new MutableMetricContainer <IDoubleGauge>(
                (name, desc) => metricsFactory.CreateDoubleGauge(name, desc),
                this);
            _rates = new MutableMetricContainer <IRate>(
                (name, desc) => metricsFactory.CreateRateMetric(name, desc),
                this);
        }
예제 #7
0
 public GetChildrenPerformanceInstrumentation(IMetricsFactory metricsFactory)
 {
     this.getChildrenFailure     = metricsFactory.Create0D("getChildrenFailure");
     this.getChildrenSuccess     = metricsFactory.Create0D("getChildrenSuccess");
     this.getChildrenResultCount = metricsFactory.Create0D("getChildrenResultCount");
     this.getChildrenLatencyMs   = metricsFactory.Create0D("getChildrenLatencyMs");
 }
        public void TestDefaultMetricsSourceExternalMetricsSubscription()
        {
            const string evalId                 = "evalId";
            const string taskId                 = "taskId";
            const string sourceContext          = "test";
            const string recordName             = "testrecord";
            const string subscribedCounterName  = "subscribedcounter";
            const long   subscribedCounterValue = 1001;

            DefaultMetricsSourceImpl metricsSource = TangFactory.GetTang().NewInjector(
                GenerateMetricsSourceConfiguration(evalId, taskId, sourceContext, recordName))
                                                     .GetInstance <DefaultMetricsSourceImpl>();

            IMetricsFactory factory = TangFactory.GetTang().NewInjector().GetInstance <IMetricsFactory>();

            MetricTestUtils.MetricsCollectorTestImpl collector = new MetricTestUtils.MetricsCollectorTestImpl();

            var extraCounter = factory.CreateCounter(subscribedCounterName,
                                                     subscribedCounterName,
                                                     subscribedCounterValue);

            extraCounter.Subscribe(metricsSource);

            metricsSource.GetMetrics(collector, true);
            var rb = collector.CurrentRecordBuilder;

            rb.Validate(subscribedCounterName, subscribedCounterValue);

            extraCounter.Increment();
            extraCounter.OnCompleted(); // This should remove the counter from the metrics source.
            metricsSource.GetMetrics(collector, true);
            rb = collector.CurrentRecordBuilder;
            Assert.False(rb.LongKeyPresent(subscribedCounterName), "The counter should not be present now in the source");
        }
        public Tracer.Builder GetTracerBuilder()
        {
            if (ReporterConfig == null)
            {
                ReporterConfig = new ReporterConfiguration(_loggerFactory);
            }
            if (SamplerConfig == null)
            {
                SamplerConfig = new SamplerConfiguration(_loggerFactory);
            }
            if (_codecConfig == null)
            {
                _codecConfig = new CodecConfiguration(new Dictionary <IFormat <ITextMap>, List <Codec <ITextMap> > >());
            }
            if (_metricsFactory == null)
            {
                _metricsFactory = NoopMetricsFactory.Instance;
            }
            IMetrics  metrics  = new MetricsImpl(_metricsFactory);
            IReporter reporter = ReporterConfig.GetReporter(metrics);
            ISampler  sampler  = SamplerConfig.CreateSampler(_serviceName, metrics);

            Tracer.Builder builder = new Tracer.Builder(_serviceName)
                                     .WithLoggerFactory(_loggerFactory)
                                     .WithSampler(sampler)
                                     .WithReporter(reporter)
                                     .WithMetrics(metrics)
                                     .WithTags(_tracerTags);

            _codecConfig.Apply(builder);

            return(builder);
        }
예제 #10
0
 public WatcherPerformanceInstrumentation(IMetricsFactory metricsFactory)
 {
     this.nodesLoaded         = metricsFactory.Create0D("watcherPerformanceTestNodesLoaded");
     this.setWatcherFailed    = metricsFactory.Create0D("setWatcherFailed");
     this.setWatcherSucceeded = metricsFactory.Create0D("setWatcherSucceded");
     this.setWatcherLatencyMs = metricsFactory.Create0D("setWatcherLatencyMs");
     this.watcherNotified     = metricsFactory.Create1D("watcherNotified", "notificationType");
 }
예제 #11
0
 public ConnectPerformanceInstrumentation(IMetricsFactory metricsFactory)
 {
     this.totalConnectionsCreated = metricsFactory.Create0D("totalConnectionsCreated");
     this.connectionEstablished   = metricsFactory.Create0D("connectionEstablished");
     this.connectionFailed        = metricsFactory.Create0D("connectionFailed");
     this.connectionClosed        = metricsFactory.Create0D("connectionClosed");
     this.connectionSetupTimeMs   = metricsFactory.Create0D("connectionSetupTimeMs");
 }
예제 #12
0
 public TypedMessagePublisher(IMetricsFactory <TypedMessagePublisher <TOutput, TPublisher> >?metrics,
                              TPublisher bytesMessagePublisher, IMessageSerializer <TOutput> messageSerializer)
 {
     _bytesMessagePublisher = bytesMessagePublisher;
     _messageSerializer     = messageSerializer;
     _messageSerialization  =
         metrics?.CreateSummary("message_serialization", "Message serialization duration in ms");
 }
예제 #13
0
        public MetricsImpl(IMetricsFactory factory)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            CreateMetrics(factory);
        }
 public MultiOutputServiceAdapter(ILogger <SingleOutputServiceAdapter <TInput, TOutput> > logger,
                                  IMetricsFactory <SingleOutputServiceAdapter <TInput, TOutput> >?metrics,
                                  IMultiOutputService <TInput, TOutput> converter,
                                  ITypedMessagePublisher <TOutput> publisher)
 {
     _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
     _converter         = converter ?? throw new ArgumentNullException(nameof(converter));
     _publisher         = publisher ?? throw new ArgumentNullException(nameof(publisher));
     _messageProcessing = metrics?.CreateSummary("message_processing", "Message processing duration in ms");
 }
        public ServiceWithMetrics(IMetricsFactory <ServiceWithMetrics> metricFactory,
                                  IServiceInDifferentNamespace serviceInDifferentNamespace)
        {
            _serviceInDifferentNamespace = serviceInDifferentNamespace;

            // Resulting label in Prometheus: metricsexample_emtpy_string_total
            _counter = metricFactory?.CreateCounter("empty_string_total",
                                                    "Counts the total number of recieved empty strings.");

            // Resulting label in Prometheus: metricsexample_fancy_number
            _summary = metricFactory?.CreateSummary("fancy_number",
                                                    "Shows the distribution of fancy numbers.");
        }
예제 #16
0
 public TypedMessagePublisher(IMetricsFactory <TypedMessagePublisher <TOutput, TPublisher> >?metrics,
                              TPublisher bytesMessagePublisher, IMessageSerializer <TOutput> messageSerializer,
                              IOptions <ContentEncodingOptions> encodingOptions, IMessageEncoder messageEncoder)
 {
     _bytesMessagePublisher = bytesMessagePublisher;
     _messageSerializer     = messageSerializer;
     _encodingOptions       = encodingOptions.Value;
     _messageEncoder        = messageEncoder;
     _messageSerialization  =
         metrics?.CreateSummary("message_serialization", "Message serialization duration in ms");
     _messageEncoding =
         metrics?.CreateSummary("message_encoding", "Message encoding duration in ms");
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="RingMasterServerInstrumentation"/> class.
        /// </summary>
        /// <param name="metricsFactory">Metrics factory for getting notification of internal state</param>
        public RingMasterServerInstrumentation(IMetricsFactory metricsFactory)
        {
            if (metricsFactory == null)
            {
                throw new ArgumentNullException(nameof(metricsFactory));
            }

            this.sessionCreated  = metricsFactory.Create1D(nameof(this.sessionCreated), "client");
            this.sessionClosed   = metricsFactory.Create1D(nameof(this.sessionClosed), "client");
            this.responseTime    = metricsFactory.Create1D(nameof(this.responseTime), "requestType");
            this.badRequests     = metricsFactory.Create0D(nameof(this.badRequests));
            this.watcherSet      = metricsFactory.Create0D(nameof(this.watcherSet));
            this.watcherNotified = metricsFactory.Create0D(nameof(this.watcherNotified));
        }
예제 #18
0
 public KafkaMessageConsumer(ILogger <KafkaMessageConsumer <TData> > logger,
                             IOptions <KafkaConsumerConfig <TData> > config,
                             IMetricsFactory <KafkaMessageConsumer <TData> >?metricsFactory,
                             IApplicationNameService applicationNameService,
                             ICloudEventFormatter cloudEventFormatter)
 {
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _applicationNameService = applicationNameService ?? throw new ArgumentNullException(nameof(config));
     _cloudEventFormatter    = cloudEventFormatter;
     _config             = config?.Value ?? throw new ArgumentNullException(nameof(config));
     _consumerLagSummary = metricsFactory?.CreateSummary("consumer_lag_distribution",
                                                         "Contains a summary of current consumer lag of each partition", new [] { "topic", "partition" });
     _consumerLagGauge = metricsFactory?.CreateGauge("consumer_lag",
                                                     "Contains current number consumer lag of each partition", false, "topic", "partition");
 }
예제 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RingMasterService"/> class.
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="ringMasterMetricsFactory">Metrics factory for MDM</param>
        /// <param name="persistenceMetricsFactory">Metrics factory for persistence</param>
        public RingMasterService(StatefulServiceContext context, IMetricsFactory ringMasterMetricsFactory, IMetricsFactory persistenceMetricsFactory)
            : base(context, PersistedDataFactory.CreateStateManager(context))
        {
            var path    = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var builder = new ConfigurationBuilder().SetBasePath(Path.GetDirectoryName(path)).AddJsonFile("appSettings.json");

            appSettings = builder.Build();

            RingMasterBackendCore.GetSettingFunction = GetSetting;
            string factoryName = $"{this.Context.ServiceTypeName}-{this.Context.ReplicaId}-{this.Context.NodeContext.NodeName}";

            this.zooKeeperServerInstrumentation  = new ZooKeeperServerInstrumentation(ringMasterMetricsFactory);
            this.ringMasterServerInstrumentation = new RingMasterServerInstrumentation(ringMasterMetricsFactory);

            var ringMasterInstrumentation  = new RingMasterBackendInstrumentation(ringMasterMetricsFactory);
            var persistenceInstrumentation = new ServiceFabricPersistenceInstrumentation(persistenceMetricsFactory);

            RingMasterBackendCoreInstrumentation.Instance = ringMasterInstrumentation;

            bool needFixStatDuringLoad    = bool.TryParse(GetSetting("WinFabPersistence.FixStatDuringLoad"), out needFixStatDuringLoad) && needFixStatDuringLoad;
            var  persistenceConfiguration = new PersistedDataFactory.Configuration
            {
                EnableActiveSecondary = true,
                FixStatDuringLoad     = needFixStatDuringLoad,
            };

            bool useInMemoryPersistence;

            if (bool.TryParse(GetSetting("InMemoryPersistence"), out useInMemoryPersistence) && useInMemoryPersistence)
            {
                this.factory = new InMemoryFactory();
            }
            else
            {
                this.factory = new PersistedDataFactory(
                    this.StateManager,
                    factoryName,
                    persistenceConfiguration,
                    persistenceInstrumentation,
                    this.cancellationSource.Token);
            }

            this.backend = new RingMasterBackendCore(this.factory);

            this.factory.SetBackend(this.backend);

            this.executor = this.backend;
        }
예제 #20
0
        private void CreateMetrics(IMetricsFactory factory)
        {
            foreach (PropertyInfo property in typeof(MetricsImpl).GetProperties())
            {
                Type metricType = property.PropertyType;

                if (!typeof(ICounter).IsAssignableFrom(metricType) &&
                    !typeof(ITimer).IsAssignableFrom(metricType) &&
                    !typeof(IGauge).IsAssignableFrom(metricType))
                {
                    // Some frameworks dynamically add code that this reflection will pick up
                    // I only want this classes Stats based fields to be picked up.
                    continue;
                }

                StringBuilder metricBuilder      = new StringBuilder("jaeger:");
                Dictionary <string, string> tags = new Dictionary <string, string>();

                var metricAttributes = property.GetCustomAttributes <MetricAttribute>();
                foreach (MetricAttribute metricAttribute in metricAttributes)
                {
                    metricBuilder.Append(metricAttribute.Name);
                    foreach (var tag in metricAttribute.Tags)
                    {
                        tags[tag.Key] = tag.Value;
                    }
                }

                string metricName = metricBuilder.ToString();

                if (metricType == typeof(ICounter))
                {
                    property.SetValue(this, factory.CreateCounter(metricName, tags));
                }
                else if (metricType == typeof(IGauge))
                {
                    property.SetValue(this, factory.CreateGauge(metricName, tags));
                }
                else if (metricType == typeof(ITimer))
                {
                    property.SetValue(this, factory.CreateTimer(metricName, tags));
                }
                else
                {
                    throw new NotSupportedException($"'{metricType}' for metric '{property.Name}' is not supported.");
                }
            }
        }
예제 #21
0
 public TwitchBotWorker(
     ITwitchCredentialsProvider credentialsProvider,
     IEnumerable <ITwitchCommandHandler> handlers,
     IMessageArchiver messageArchiver,
     IChatMessageStorage chatMessageStorage,
     IMetricsFactory metricsFactory,
     ILogger <TwitchBotWorker> logger)
 {
     this.credentialsProvider = credentialsProvider;
     this.commandHandlers     = handlers.ToDictionary(
         h => h.CommandName,
         h => h);
     this.messageArchiver    = messageArchiver;
     this.chatMessageStorage = chatMessageStorage;
     this.metricsFactory     = metricsFactory;
     this.logger             = logger;
 }
예제 #22
0
        /// <summary>
        /// Initializes the specified environment.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <param name="tenant">The tenant.</param>
        /// <param name="mdmAccountName">Name of the MDM account.</param>
        /// <param name="roleInstance">The role instance.</param>
        /// <param name="roleName">Name of the role.</param>
        /// <param name="sessionName">Name of the session.</param>
        /// <param name="mdmNamespace">The MDM namespace.</param>
        /// <param name="enableMdm">if set to <c>true</c> [MDM enabled].</param>
        public static void Initialize(string environment, string tenant, string mdmAccountName, string roleInstance, string roleName, string sessionName, string mdmNamespace, bool enableMdm)
        {
            mdmEnabled = enableMdm;

            if (mdmEnabled)
            {
                IfxInstrumentation.Initialize(sessionName, mdmAccountName);
                metricsFactory = IfxInstrumentation.CreateMetricsFactory(mdmAccountName, mdmNamespace, environment, tenant, roleName, roleInstance);

                InitializeMetrics();
                System.Console.WriteLine("MDM enabled");
            }
            else
            {
                System.Console.WriteLine("MDM disaabled");
            }
        }
예제 #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RingMasterWatchdog"/> class.
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="metricsFactory">Metric factory for MDM</param>
        public RingMasterWatchdog(StatelessServiceContext context, IMetricsFactory metricsFactory)
            : base(context)
        {
            if (metricsFactory == null)
            {
                throw new ArgumentNullException(nameof(metricsFactory));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            System.Diagnostics.Contracts.Contract.EndContractBlock();

            this.ringMasterWatchdogTestSucceeded = metricsFactory.Create1D(nameof(this.ringMasterWatchdogTestSucceeded), "testName");
            this.ringMasterServiceUri            = new Uri($"{context.CodePackageActivationContext.ApplicationName}/RingMasterService");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceFabricPersistenceInstrumentation"/> class.
        /// </summary>
        /// <param name="metricsFactory">Metrics factory</param>
        public ServiceFabricPersistenceInstrumentation(IMetricsFactory metricsFactory)
        {
            if (metricsFactory == null)
            {
                throw new ArgumentNullException(nameof(metricsFactory));
            }

            this.addRequested    = metricsFactory.Create0D(nameof(this.addRequested));
            this.updateRequested = metricsFactory.Create0D(nameof(this.updateRequested));
            this.removeRequested = metricsFactory.Create0D(nameof(this.removeRequested));

            this.loadTreeCompleted = metricsFactory.Create0D(nameof(this.loadTreeCompleted));
            this.loadTreeTime      = metricsFactory.Create0D(nameof(this.loadTreeTime));

            this.processLoadCompleted   = metricsFactory.Create0D(nameof(this.processLoadCompleted));
            this.processAddCompleted    = metricsFactory.Create0D(nameof(this.processAddCompleted));
            this.processUpdateCompleted = metricsFactory.Create0D(nameof(this.processUpdateCompleted));
            this.processRemoveCompleted = metricsFactory.Create0D(nameof(this.processRemoveCompleted));
            this.processLoadFailed      = metricsFactory.Create0D(nameof(this.processLoadFailed));
            this.processAddFailed       = metricsFactory.Create0D(nameof(this.processAddFailed));
            this.processUpdateFailed    = metricsFactory.Create0D(nameof(this.processUpdateFailed));
            this.processRemoveFailed    = metricsFactory.Create0D(nameof(this.processRemoveFailed));

            this.dictionaryEntriesEnumerated       = metricsFactory.Create0D(nameof(this.dictionaryEntriesEnumerated));
            this.processDictionaryRebuildCompleted = metricsFactory.Create0D(nameof(this.processDictionaryRebuildCompleted));
            this.processDictionaryRebuildTime      = metricsFactory.Create0D(nameof(this.processDictionaryRebuildTime));
            this.processDictionaryRebuildFailed    = metricsFactory.Create0D(nameof(this.processDictionaryRebuildFailed));

            this.totalNodes    = metricsFactory.Create0D(nameof(this.totalNodes));
            this.totalDataSize = metricsFactory.Create0D(nameof(this.totalDataSize));

            this.transactionCommitted     = metricsFactory.Create0D(nameof(this.transactionCommitted));
            this.lastCommittedTransaction = metricsFactory.Create0D(nameof(this.lastCommittedTransaction));
            this.lastCommitSequenceNumber = metricsFactory.Create0D(nameof(this.lastCommitSequenceNumber));

            this.changeListCommitted    = metricsFactory.Create0D(nameof(this.changeListCommitted));
            this.changeListCommitFailed = metricsFactory.Create0D(nameof(this.changeListCommitFailed));
            this.changeListAborted      = metricsFactory.Create0D(nameof(this.changeListAborted));
            this.changeListCommitTime   = metricsFactory.Create0D(nameof(this.changeListCommitTime));

            this.dataLoaded      = metricsFactory.Create0D(nameof(this.dataLoaded));
            this.duplicatesFound = metricsFactory.Create0D(nameof(this.duplicatesFound));
            this.orphansFound    = metricsFactory.Create0D(nameof(this.orphansFound));
        }
        public Tracer.Builder GetTracerBuilder()
        {
            if (ReporterConfig == null)
            {
                ReporterConfig = new ReporterConfiguration(_loggerFactory);
            }
            if (SamplerConfig == null)
            {
                SamplerConfig = new SamplerConfiguration(_loggerFactory);
            }
            if (CodecConfig == null)
            {
                CodecConfig = new CodecConfiguration(_loggerFactory);
            }
            if (_metricsFactory == null)
            {
                _metricsFactory = NoopMetricsFactory.Instance;
            }
            IMetrics  metrics  = new MetricsImpl(_metricsFactory);
            IReporter reporter = ReporterConfig.GetReporter(metrics);
            ISampler  sampler  = SamplerConfig.GetSampler(ServiceName, metrics);

            Tracer.Builder builder = new Tracer.Builder(ServiceName)
                                     .WithLoggerFactory(_loggerFactory)
                                     .WithSampler(sampler)
                                     .WithReporter(reporter)
                                     .WithMetrics(metrics)
                                     .WithTags(_tracerTags);

            if (UseTraceId128Bit)
            {
                builder = builder.WithTraceId128Bit();
            }

            CodecConfig.Apply(builder);

            return(builder);
        }
예제 #26
0
 public DiscordBotWorker(
     DiscordSocketClient discordSocketClient,
     IDiscordCredentialProvider credentialProvider,
     IEnumerable <IDiscordCommandHandler> commandHandlers,
     IMessageArchiver messageArchiver,
     IChatMessageStorage chatMessageStorage,
     IMetricsFactory metricsFactory,
     ILogger <DiscordBotWorker> logger)
 {
     this.credentialProvider = credentialProvider;
     this.commandHandlers    = commandHandlers
                               .ToDictionary(
         ch => ch.CommandName,
         ch => ch);
     this.socketClient                  = discordSocketClient;
     this.socketClient.Log             += WebhookClientOnLog;
     this.socketClient.Ready           += WebhookClientOnReady;
     this.socketClient.MessageReceived += WebhookClientOnMessageReceived;
     this.messageArchiver               = messageArchiver;
     this.chatMessageStorage            = chatMessageStorage;
     this.metricsFactory                = metricsFactory;
     this.logger = logger;
 }
예제 #27
0
        public void TestMetricsTagClass()
        {
            const string    name          = "tagtest";
            const string    otherName     = "othertagtest";
            const string    desc          = "tagtestdesc";
            const string    otherDesc     = "othertagtestdesc";
            const string    tagValue      = "tagvalue";
            const string    otherTagValue = "othertagvalue";
            IMetricsFactory factory       = TangFactory.GetTang().NewInjector().GetInstance <IMetricsFactory>();

            IMetricsInfo info = new MetricsInfoImpl(name, desc);
            MetricsTag   tag  = factory.CreateTag(info, tagValue);

            Assert.Equal(name, tag.Name);
            Assert.Equal(desc, tag.Description);
            Assert.Equal(tagValue, tag.Value);

            MetricsTag sameTag = factory.CreateTag(info, tagValue);

            Assert.True(tag.Equals(sameTag));

            MetricsTag otherTag = factory.CreateTag(info, otherTagValue);

            Assert.False(tag.Equals(otherTag));

            otherTag = factory.CreateTag(new MetricsInfoImpl(otherName, desc), tagValue);
            Assert.False(tag.Equals(otherTag));

            otherTag = factory.CreateTag(new MetricsInfoImpl(name, otherDesc), otherTagValue);
            Assert.False(tag.Equals(otherTag));

            string expectedToString = "Tag Information: " + "Name: " + info.Name + ", Description: " + info.Description +
                                      ", Tag Value: " + tagValue;

            Assert.Equal(expectedToString, tag.ToString());
        }
예제 #28
0
 public PrometheusDelegatingHandler(IMetricsFactory <PrometheusDelegatingHandler> metricsFactory)
 {
     _requestTotal =
         metricsFactory.CreateCounter("request_total", "number of external request", false, "host", "status");
     _requestLatency = metricsFactory.CreateSummary("request_latency", "request duration in ms", new[] { "host" });
 }
 public ReverseStringConverter(ILogger <ReverseStringConverter> logger,
                               IMetricsFactory <ReverseStringConverter> metricsFactory)
 {
     _logger  = logger;
     _summary = metricsFactory.CreateSummary("summaryName", "summaryHelpString", new[] { "someLabel" });
 }
예제 #30
0
 public EnumerationStressService(StatelessServiceContext context, IMetricsFactory metricsFactory)
     : base(context)
 {
     this.MetricsFactory = metricsFactory;
 }
 public void WithMetricsFactory(IMetricsFactory metricsFactory)
 {
     _metricsFactory = metricsFactory;
 }