public static async Task <T> Profile <T>(TimerOptions timer, Func <Task <T> > task) { using (_metrics.Measure.Timer.Time(timer)) { return(await task().ConfigureAwait(false)); } }
/// <summary> /// Adds the item to the cache /// </summary> /// <param name="id">The identifier of the item</param> /// <param name="item">The item to be added</param> /// <param name="culture">The culture of the data-transfer-object</param> /// <param name="dtoType">Type of the dto item</param> /// <param name="requester">The cache item which invoked request</param> /// <returns><c>true</c> if is added/updated, <c>false</c> otherwise</returns> public Task <bool> CacheAddDtoAsync(URN id, object item, CultureInfo culture, DtoType dtoType, ISportEventCI requester) { Guard.Argument(id, nameof(id)).NotNull(); Guard.Argument(item, nameof(item)).NotNull(); var timerOptionsCache = new TimerOptions { Context = "SdkCache", Name = $"SaveTo_{CacheName}", MeasurementUnit = Unit.Calls }; var timerOptionsDtType = new TimerOptions { Context = "SdkCache", Name = $"{dtoType}", MeasurementUnit = Unit.Calls }; using (_metrics.Measure.Timer.Time(timerOptionsCache)) { using (_metrics.Measure.Timer.Time(timerOptionsDtType)) { //WriteLog($"{CacheName} ::> Saving DTO for id:{id}, lang:[{culture.TwoLetterISOLanguageName}] and type:{dtoType}."); var syncTask = new Task <bool>(() => { var result = CacheAddDtoItem(id, item, culture, dtoType, requester); //WriteLog($"{CacheName} ::> Saving DTO for id:{id}, lang:[{culture.TwoLetterISOLanguageName}] and type:{dtoType} COMPLETED."); return(result); }); syncTask.Start(); return(syncTask); } } }
public TimedRulesDriver(IRulesDriver rulesDriver, Func <IMetrics> metrics, string timerContext = "RulesDriver") { _rulesDriver = rulesDriver; _metrics = new Lazy <IMetrics>(metrics); _getVersionTimer = timerContext.GetTimer("GetVersion"); _getRulesetTimer = timerContext.GetTimer("GetRuleset"); }
public static async Task Profile(TimerOptions timer, Func <Task> task) { using (_metrics.Measure.Timer.Time(timer)) { await task().ConfigureAwait(false); } }
/// <inheritdoc /> public void Time(TimerOptions options, Action action, string userValue) { using (_registry.Timer(options, () => Advanced.BuildTimer(options)).NewContext(userValue)) { action(); } }
public QueueProcessor( ConnectionFactory queueConnectionFactory, ILogger <IQueueProcessor> logger, IRiverFlowProcessor riverFlowProcessor, IMetrics metrics, IOptions <QueueConfig> queueOptions) { this.queueConnectionFactory = queueConnectionFactory; this.queueConnectionFactory.DispatchConsumersAsync = true; this.logger = logger; this.riverFlowProcessor = riverFlowProcessor; this.metrics = metrics; this.queueConfig = queueOptions.Value.Validate(); this.queueProcessTimer = new TimerOptions { Name = "Queue Processing Timer", MeasurementUnit = App.Metrics.Unit.Calls, DurationUnit = TimeUnit.Seconds, RateUnit = TimeUnit.Minutes }; this.failureCounter = new CounterOptions { Name = "Queue Processing Failures", MeasurementUnit = App.Metrics.Unit.Errors, ReportItemPercentages = true }; }
public async Task TimeToCreateSingleDB() { var timerOptionsStart = new TimerOptions { Name = "sqlite-provision", MeasurementUnit = Unit.Commands, DurationUnit = TimeUnit.Milliseconds, RateUnit = TimeUnit.Milliseconds }; var tempFileName = "c:/dev/temp/spike1.db"; var connectionString = $"Data Source={tempFileName};Cache=Shared;"; var connection = new SqliteConnection(connectionString); _metrics.Measure.Timer.Time(timerOptionsStart); using (_metrics.Measure.Timer.Time(timerOptionsStart)) { await ExecuteNonQueryAsync(connection, DropTables); await ExecuteNonQueryAsync(connection, CreateTables); } await Task.WhenAll(_metrics.ReportRunner.RunAllAsync()); }
public async Task TimeToCreateDatabase() { var tempFileName = Path.GetTempFileName(); var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = tempFileName, Cache = SqliteCacheMode.Shared, Mode = SqliteOpenMode.ReadWriteCreate, }; var connectionString = connectionStringBuilder.ConnectionString; var connection = new SqliteConnection(connectionString); var timerOptions = new TimerOptions { Name = "sqlite-db-create", MeasurementUnit = Unit.Commands, DurationUnit = TimeUnit.Milliseconds, RateUnit = TimeUnit.Milliseconds }; for (int i = 0; i < 100; i++) { using (_metrics.Measure.Timer.Time(timerOptions)) { await ExecuteNonQueryAsync(connection, CreateTables); } File.Delete(tempFileName); } await Task.WhenAll(_metrics.ReportRunner.RunAllAsync()); }
private void OnRawFeedMessageReceived(object sender, RawFeedMessageEventArgs e) { if (RawFeedMessageReceived == null) { return; } var timerOptionsOnRawFeedMessageReceived = new TimerOptions { Context = "FeedExt", Name = "OnRawFeedMessageReceived", MeasurementUnit = Unit.Items }; using var t = MetricsRoot.Measure.Timer.Time(timerOptionsOnRawFeedMessageReceived, $"{e.MessageInterest} - {e.FeedMessage?.EventId}"); try { RawFeedMessageReceived?.Invoke(sender, e); var requestId = e.FeedMessage?.RequestId == null ? null : $" ({e.FeedMessage.RequestId})"; Log.LogInformation($"Dispatching raw feed message [{e.MessageInterest}]: {e.FeedMessage?.GetType().Name} for event {e.FeedMessage?.EventId}{requestId} took {t.Elapsed.TotalMilliseconds} ms."); } catch (Exception ex) { Log.LogError(ex, $"Error dispatching raw feed message [{e.MessageInterest}] for {e.RoutingKey} and {e.FeedMessage?.EventId}. Took {t.Elapsed.TotalMilliseconds} ms."); } }
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" }; }
protected async Task MeasureTimeAsync(Func <Task> fn, TimerOptions timerOptions) { using (_metrics?.Measure.Timer.Time(timerOptions)) { await fn(); } }
/// <summary> /// Returns an <see cref="CommandLineArguments"/> instance based on the factory default settings. /// </summary> /// <returns>An <see cref="CommandLineArguments"/> instance based on the factory default settings.</returns> private static CommandLineArguments GetArgumentsFromFactoryDefaults() { TimerOptions defaultOptions = new TimerOptions(); WindowSize mostRecentWindowSize = GetMostRecentWindowSize(); Rect defaultWindowBounds = defaultOptions.WindowSize.RestoreBounds; Rect defaultWindowBoundsWithLocation = mostRecentWindowSize.RestoreBounds.Merge(defaultWindowBounds); return(new CommandLineArguments { Title = defaultOptions.Title, AlwaysOnTop = defaultOptions.AlwaysOnTop, IsFullScreen = defaultOptions.WindowSize.IsFullScreen, ShowInNotificationArea = false, LoopTimer = defaultOptions.LoopTimer, PopUpWhenExpired = defaultOptions.PopUpWhenExpired, CloseWhenExpired = defaultOptions.CloseWhenExpired, Color = defaultOptions.Color, Sound = defaultOptions.Sound, LoopSound = defaultOptions.LoopSound, WindowState = defaultOptions.WindowSize.WindowState, RestoreWindowState = defaultOptions.WindowSize.RestoreWindowState, WindowBounds = defaultWindowBoundsWithLocation }); }
internal DotNetEventListener(IEventSourceStatsCollector collector, Action <Exception> errorHandler, bool enableDebugging, IMetrics metrics) : base() { _collector = collector; _errorHandler = errorHandler; _enableDebugging = enableDebugging; _metrics = metrics; if (_enableDebugging) { _cpuConsumed = new TimerOptions() { Context = DotNetRuntimeMetricsRegistry.ContextName, MeasurementUnit = Unit.None, DurationUnit = TimeUnit.Nanoseconds, Name = "dotnet_debug_cpu_nanoseconds_total", Tags = new MetricTags("collector", collector.GetType().Name.ToSnakeCase()) }; } _eventTypeCounts = new CounterOptions() { Context = DotNetRuntimeMetricsRegistry.ContextName, MeasurementUnit = Unit.Items, ReportItemPercentages = false }; EventSourceCreated += OnEventSourceCreated; }
protected T MeasureTime <T>(Func <T> fn, TimerOptions timerOptions) { using (_metrics?.Measure.Timer.Time(timerOptions)) { return(fn()); } }
public RiverFlowProcessor( IUsgsIvClient usgsIvClient, IFlowClient flowClient, ILogger <IRiverFlowProcessor> logger, IMetrics metrics) { this.usgsIvClient = usgsIvClient; this.flowClient = flowClient; this.logger = logger; this.metrics = metrics; this.requestTimer = new TimerOptions { Name = "River Flow Queries", MeasurementUnit = App.Metrics.Unit.Calls, DurationUnit = TimeUnit.Seconds, RateUnit = TimeUnit.Minutes }; this.recordTimer = new TimerOptions { Name = "River Flow Recordings", MeasurementUnit = App.Metrics.Unit.Calls, DurationUnit = TimeUnit.Seconds, RateUnit = TimeUnit.Minutes }; }
public void can_use_custom_reservoir_when_multidimensional() { var reservoirMock = new Mock <IReservoir>(); reservoirMock.Setup(r => r.Update(It.IsAny <long>(), null)); reservoirMock.Setup(r => r.GetSnapshot()).Returns(() => new UniformSnapshot(100L, 100.0, new long[100])); reservoirMock.Setup(r => r.Reset()); var reservoir = new Lazy <IReservoir>(() => reservoirMock.Object); var options = new TimerOptions { Name = "timer_provider_custom_test_multi", Reservoir = reservoir }; var timer = _provider.Instance(options, _fixture.Tags[0]); using (timer.NewContext()) { _fixture.Clock.Advance(TimeUnit.Milliseconds, 100); } reservoirMock.Verify(r => r.Update(It.IsAny <long>(), null), Times.Once); }
internal virtual Option <JObject> EncryptKeyAndBuildResult( IAmazonKeyManagementService kmsClient, string region, string arn, byte[] dataKeyPlainText) { try { TimerOptions encryptTimerOptions = new TimerOptions { Name = MetricsUtil.AelMetricsPrefix + ".kms.aws.encrypt." + region }; using (MetricsUtil.MetricsInstance.Measure.Timer.Time(encryptTimerOptions)) { // Note we can't wipe plaintext key till end of calling method since underlying buffer shared by all requests EncryptRequest encryptRequest = new EncryptRequest { KeyId = arn, Plaintext = new MemoryStream(dataKeyPlainText) }; Task <EncryptResponse> encryptAsync = kmsClient.EncryptAsync(encryptRequest); byte[] encryptedKeyEncryptionKey = encryptAsync.Result.CiphertextBlob.ToArray(); return(Option <JObject> .Some(BuildKmsRegionKeyJson(region, arn, encryptedKeyEncryptionKey))); } } catch (AggregateException e) { Logger.LogWarning(e, "Failed to encrypt generated data key via region {region} KMS", region); // TODO Consider adding notification/CW alert return(Option <JObject> .None); } }
/// <summary> /// Attempt to generate a KMS datakey using the first successful response using a sorted dictionary of available KMS clients. /// </summary> /// <param name="sortedRegionToArnAndClientDictionary"> A sorted dictionary mapping regions and their arns and kms clients</param> /// <param name="dateKeyKeyId">The KMS arn used to generate the data key</param> /// <returns>A GenerateDataKeyResult object that contains the plain text key and the ciphertext for that key</returns> /// <exception cref="KeyManagementException">Throw an exception if we're unable to generate a datakey in any AWS region</exception> internal virtual GenerateDataKeyResult GenerateDataKey(OrderedDictionary sortedRegionToArnAndClientDictionary, out string dateKeyKeyId) { foreach (DictionaryEntry regionToArnAndClient in sortedRegionToArnAndClientDictionary) { try { TimerOptions generateDataKeyTimerOptions = new TimerOptions { Name = MetricsUtil.AelMetricsPrefix + ".kms.aws.generatedatakey." + regionToArnAndClient.Key }; using (MetricsUtil.MetricsInstance.Measure.Timer.Time(generateDataKeyTimerOptions)) { IAmazonKeyManagementService client = ((AwsKmsArnClient)regionToArnAndClient.Value).AwsKmsClient; string keyIdForDataKeyGeneration = ((AwsKmsArnClient)regionToArnAndClient.Value).Arn; GenerateDataKeyResult generateDataKeyResult = client.GenerateDataKey( keyIdForDataKeyGeneration, null, DataKeySpec.AES_256); dateKeyKeyId = keyIdForDataKeyGeneration; return(generateDataKeyResult); } } catch (AmazonServiceException e) { Logger.LogWarning(e, "Failed to generate data key via region {region}, trying next region", regionToArnAndClient.Key); // TODO Consider adding notification/CW alert } } throw new KeyManagementException("could not successfully generate data key using any regions"); }
public void Multidimensional_should_not_share_reservoir_when_changed_from_default() { var timerDef = new TimerOptions { Reservoir = () => new DefaultForwardDecayingReservoir() }; using (var metricsFixture = new MetricsFixture()) { var timer1 = metricsFixture.Metrics.Provider.Timer.Instance(timerDef, new MetricTags("test", "1")); var unused = metricsFixture.Metrics.Provider.Timer.Instance(timerDef, new MetricTags("test", "2")); timer1.Record(100, TimeUnit.Seconds); timer1.Record(100, TimeUnit.Seconds); timer1.Record(100, TimeUnit.Seconds); timer1.Record(100, TimeUnit.Seconds); timer1.Record(100, TimeUnit.Seconds); var timers = metricsFixture.Metrics.Snapshot.Get().Contexts.First().Timers.ToArray(); Assert.Equal(5, timers[0].Value.Histogram.Count); Assert.Equal(100_000, timers[0].Value.Histogram.Mean); Assert.Equal(0, timers[1].Value.Histogram.Mean); Assert.Equal(0, timers[1].Value.Histogram.Count); } }
/// <summary> /// Adds the item to the cache /// </summary> /// <param name="id">The identifier of the item</param> /// <param name="item">The item to be added</param> /// <param name="culture">The culture of the data-transfer-object</param> /// <param name="dtoType">Type of the dto item</param> /// <param name="requester">The cache item which invoked request</param> /// <returns><c>true</c> if is added/updated, <c>false</c> otherwise</returns> public Task <bool> CacheAddDtoAsync(URN id, object item, CultureInfo culture, DtoType dtoType, ISportEventCI requester) { Guard.Argument(id, nameof(id)).NotNull(); Guard.Argument(item, nameof(item)).NotNull(); var timerOptionsCache = new TimerOptions { Context = "SdkCache", Name = $"SaveTo_{CacheName}", MeasurementUnit = Unit.Calls }; var timerOptionsDtType = new TimerOptions { Context = "SdkCache", Name = $"{dtoType}", MeasurementUnit = Unit.Calls }; using (_metrics.Measure.Timer.Time(timerOptionsCache)) { using (_metrics.Measure.Timer.Time(timerOptionsDtType)) { var syncTask = new Task <bool>(() => { var result = CacheAddDtoItem(id, item, culture, dtoType, requester); return(result); }); syncTask.Start(); return(syncTask); } } }
public static IDisposable Latency(MetricTags tags, TimerOptions options) { Preconditions.CheckNotNull(tags); Preconditions.CheckNotNull(options); return(MetricsCollector.Map(mroot => mroot.Measure.Timer.Time(options, tags) as IDisposable).GetOrElse(() => new NullDisposable())); }
/// <summary> /// Asynchronously gets a match stats descriptions specified by the language specified by <code>culture</code> /// </summary> /// <param name="culture">A <see cref="CultureInfo"/> specifying the language of the retrieved match statuses</param> /// <returns>A <see cref="Task" /> representing the retrieval operation</returns> private async Task FetchAndMerge(CultureInfo culture) { Guard.Argument(culture, nameof(culture)).NotNull(); EntityList <NamedValueDTO> record; var timerOptions = new TimerOptions { Context = "LocalizedNamedValueCache", Name = "GetAsync", MeasurementUnit = Unit.Requests }; using (SdkMetricsFactory.MetricsRoot.Measure.Timer.Time(timerOptions, $"{culture.TwoLetterISOLanguageName}")) { record = await _dataProvider.GetDataAsync(culture.TwoLetterISOLanguageName).ConfigureAwait(false); } lock (_lock) { foreach (var item in record.Items) { if (_namedValues.TryGetValue(item.Id, out var trans)) { trans[culture] = item.Description; } else { trans = new Dictionary <CultureInfo, string> { { culture, item.Description } }; _namedValues.Add(item.Id, trans); } } _loadedCultures.Add(culture); } CacheLog.LogDebug($"LocalizedNamedValueCache: {record.Items.Count()} items retrieved for locale '{culture.TwoLetterISOLanguageName}'."); }
public void can_time_in_using_when_multidimensional_with_user_value() { var metricName = "test_manager_timer_using_with_user_value_multi"; var options = new TimerOptions { Name = metricName }; using (_manager.Time(options, _fixture.Tags[0], "value1")) { _fixture.Clock.Advance(TimeUnit.Milliseconds, 100L); } using (_manager.Time(options, _fixture.Tags[0], "value2")) { _fixture.Clock.Advance(TimeUnit.Milliseconds, 200L); } using (_manager.Time(options, _fixture.Tags[1], "value1")) { _fixture.Clock.Advance(TimeUnit.Milliseconds, 1000L); } using (_manager.Time(options, _fixture.Tags[1], "value2")) { _fixture.Clock.Advance(TimeUnit.Milliseconds, 2000L); } _fixture.Snapshot.GetTimerValue(_fixture.Context, _fixture.Tags[0].AsMetricName(metricName)).Histogram.Sum.Should().Be(300.0); _fixture.Snapshot.GetTimerValue(_fixture.Context, _fixture.Tags[0].AsMetricName(metricName)).Histogram.MinUserValue.Should().Be("value1"); _fixture.Snapshot.GetTimerValue(_fixture.Context, _fixture.Tags[0].AsMetricName(metricName)).Histogram.MaxUserValue.Should().Be("value2"); _fixture.Snapshot.GetTimerValue(_fixture.Context, _fixture.Tags[1].AsMetricName(metricName)).Histogram.Sum.Should().Be(3000.0); _fixture.Snapshot.GetTimerValue(_fixture.Context, _fixture.Tags[1].AsMetricName(metricName)).Histogram.MinUserValue.Should().Be("value1"); _fixture.Snapshot.GetTimerValue(_fixture.Context, _fixture.Tags[1].AsMetricName(metricName)).Histogram.MaxUserValue.Should().Be("value2"); }
/// <summary> /// Gets the cached <see cref="SportEventStatusCI" /> instance associated with the sport event specified by the <code>eventId</code>. If the instance associated /// with the specified event is not found, it tries to obtain it via API, if still cant, a <see cref="SportEventStatusCI" /> instance indicating a 'not started' event is returned. /// </summary> /// <param name="eventId">A <see cref="URN" /> representing the id of the sport event whose status to get</param> /// <returns>A <see cref="SportEventStatusCI" /> representing the status of the specified sport event</returns> public async Task <SportEventStatusCI> GetSportEventStatusAsync(URN eventId) { if (_isDisposed) { return(null); } Guard.Argument(eventId, nameof(eventId)).NotNull(); var timerOptions = new TimerOptions { Context = "SportEventStatusCache", Name = "GetSportEventStatusAsync", MeasurementUnit = Unit.Requests }; using (SdkMetricsFactory.MetricsRoot.Measure.Timer.Time(timerOptions, $"{eventId}")) { try { // fetch from api await _fetchSemaphore.WaitAsync().ConfigureAwait(false); // get from cache lock (_lock) // lock needed because of adding to cache in other methods { var item = _sportEventStatusCache.Get(eventId.ToString()); if (item != null) { return((SportEventStatusCI)item); } } var cachedEvent = _sportEventCache.GetEventCacheItem(eventId) as ICompetitionCI; if (cachedEvent != null) { await cachedEvent.FetchSportEventStatusAsync().ConfigureAwait(false); } // get from cache lock (_lock) // lock needed because of adding to cache in other methods { var item = _sportEventStatusCache.Get(eventId.ToString()); if (item != null) { return((SportEventStatusCI)item); } } } finally { //var msg = $"GetSportEventStatusAsync: {eventId} returns status in {t.Elapsed.TotalMilliseconds} ms."; if (!_isDisposed) { _fetchSemaphore.Release(); } } } return(((SportEventStatusMapperBase)_mapperFactory).CreateNotStarted()); }
/// <summary> /// Returns an <see cref="CommandLineArguments"/> instance based on the factory default settings. /// </summary> /// <returns>An <see cref="CommandLineArguments"/> instance based on the factory default settings.</returns> private static CommandLineArguments GetArgumentsFromFactoryDefaults() { TimerOptions defaultOptions = new TimerOptions(); WindowSize mostRecentWindowSize = GetMostRecentWindowSize(); Rect defaultWindowBounds = defaultOptions.WindowSize.RestoreBounds; Rect defaultWindowBoundsWithLocation = mostRecentWindowSize.RestoreBounds.Merge(defaultWindowBounds); return(new CommandLineArguments { Title = defaultOptions.Title, AlwaysOnTop = defaultOptions.AlwaysOnTop, IsFullScreen = defaultOptions.WindowSize.IsFullScreen, PromptOnExit = defaultOptions.PromptOnExit, DoNotKeepComputerAwake = defaultOptions.DoNotKeepComputerAwake, ShowTimeElapsed = defaultOptions.ShowTimeElapsed, ShowInNotificationArea = false, LoopTimer = defaultOptions.LoopTimer, PopUpWhenExpired = defaultOptions.PopUpWhenExpired, CloseWhenExpired = defaultOptions.CloseWhenExpired, ShutDownWhenExpired = defaultOptions.ShutDownWhenExpired, Theme = defaultOptions.Theme, Sound = defaultOptions.Sound, LoopSound = defaultOptions.LoopSound, OpenSavedTimers = false, WindowTitleMode = WindowTitleMode.ApplicationName, WindowState = defaultOptions.WindowSize.WindowState, RestoreWindowState = defaultOptions.WindowSize.RestoreWindowState, WindowBounds = defaultWindowBoundsWithLocation }); }
/// <summary> /// Returns an <see cref="CommandLineArguments"/> instance based on the most recent options. /// </summary> /// <returns>An <see cref="CommandLineArguments"/> instance based on the most recent options.</returns> private static CommandLineArguments GetArgumentsFromMostRecentOptions() { TimerOptions options = TimerOptionsManager.Instance.MostRecentOptions; WindowSize windowSize = GetMostRecentWindowSize(); return(new CommandLineArguments { Title = null, AlwaysOnTop = options.AlwaysOnTop, IsFullScreen = windowSize.IsFullScreen, PromptOnExit = options.PromptOnExit, DoNotKeepComputerAwake = options.DoNotKeepComputerAwake, ShowTimeElapsed = options.ShowTimeElapsed, ShowInNotificationArea = Settings.Default.ShowInNotificationArea, LoopTimer = options.LoopTimer, PopUpWhenExpired = options.PopUpWhenExpired, CloseWhenExpired = options.CloseWhenExpired, ShutDownWhenExpired = options.ShutDownWhenExpired, Theme = options.Theme, Sound = options.Sound, LoopSound = options.LoopSound, OpenSavedTimers = Settings.Default.OpenSavedTimersOnStartup, WindowTitleMode = options.WindowTitleMode, WindowState = windowSize.WindowState != WindowState.Minimized ? windowSize.WindowState : windowSize.RestoreWindowState, RestoreWindowState = windowSize.RestoreWindowState, WindowBounds = windowSize.RestoreBounds }); }
protected async Task <T> MeasureTimeAsync <T>(Func <Task <T> > fn, TimerOptions timerOptions) { using (_metrics?.Measure.Timer.Time(timerOptions)) { return(await fn()); } }
public ITimer Timer <T>(TimerOptions options, Func <T> builder) where T : ITimerMetric { EnsureContextLabel(options); EnsureSamplingType(options); var registry = _contexts.GetOrAdd(options.Context, _newContextRegistry); return(registry.Timer(options, builder)); }
public Timer(IOptions <TimerOptions> config, IBackgroundTaskQueue <MotorCloudEvent <IJobExecutionContext> > queue, IApplicationNameService applicationNameService) { _queue = queue; _applicationNameService = applicationNameService; _options = config.Value ?? throw new ArgumentNullException(nameof(config)); }
public TimedContextDriver(IContextDriver contextDriver, IMetrics metrics, string timerContext = "ContextDriver") { _contextDriver = contextDriver; _metrics = metrics; _getContextTimer = timerContext.GetTimer("Get"); _appendContextTimer = timerContext.GetTimer("Append"); _removeContextTimer = timerContext.GetTimer("Remove"); }