Facebook
From iza, 4 Years ago, written in C#.
Embed
Download Paste or View Raw
Hits: 221
  1. using System;
  2. using System.Collections.Generic;
  3. using ABB.Ability.Cloud.DCS.Core.ApplicationTracking;
  4. using ABB.Ability.Common.Logging;
  5. using Microsoft.ApplicationInsights;
  6.  
  7. namespace ABB.Ability.Cloud.DCS.PlatformEventProcessor.Handler
  8. {
  9.     public class MeasureAndLogTimer : IDisposable
  10.     {
  11.         private readonly TelemetryClient _telemetryClient;
  12.         private readonly string _correlationId;
  13.         private readonly Microsoft.Extensions.Logging.ILogger<LogExecutionTimeEventProcessorHandlerDecorator> _logger;
  14.         private readonly IStopwatch _stopwatch;
  15.         private readonly DateTime _startTime;
  16.  
  17.         public MeasureAndLogTimer(string correlationId,
  18.             TelemetryClient telemetryClientProvider,
  19.             Microsoft.Extensions.Logging.ILogger<LogExecutionTimeEventProcessorHandlerDecorator> logger,
  20.             IStopwatch stopwatch)
  21.         {
  22.             _correlationId = correlationId;
  23.             _telemetryClient = telemetryClientProvider;
  24.             _logger = logger;
  25.             _stopwatch = stopwatch;
  26.             _startTime = _stopwatch.Start();
  27.             _logger.Info(correlationId, $"Start processing time: {_startTime}");
  28.         }
  29.  
  30.         public void Dispose()
  31.         {
  32.             DateTime endTime = _stopwatch.Stop();
  33.             TimeSpan elapsedTimeSpan = _stopwatch.Elapsed();
  34.             _logger.Info(_correlationId, $"Stop processing time: { endTime }. " +
  35.                                          $"Duration processing time: { elapsedTimeSpan }");
  36.  
  37.             var properties = InitializeDictionary(_startTime, endTime, elapsedTimeSpan);
  38.  
  39.             _telemetryClient.TrackEvent("Processing time: ", properties);
  40.             _telemetryClient.Flush();
  41.         }
  42.  
  43.         private Dictionary<string, string> InitializeDictionary(DateTime startTime, DateTime endTime, TimeSpan elapsedTimeSpan)
  44.         {
  45.             var properties = new Dictionary<string, string>()
  46.             {
  47.                 {"StartTime", startTime.ToString()},
  48.                 {"EndTime", endTime.ToString()},
  49.                 {"Duration", elapsedTimeSpan.ToString()}
  50.             };
  51.  
  52.             return properties;
  53.         }
  54.     }
  55. }