Skip to content

Instantly share code, notes, and snippets.

@micdenny
Created December 21, 2016 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micdenny/ce48a2ee85e74744381298a0515f1d4d to your computer and use it in GitHub Desktop.
Save micdenny/ce48a2ee85e74744381298a0515f1d4d to your computer and use it in GitHub Desktop.
Application insights extension to track an event and record the duration of it as a metric associated to the Event
public static class TelemetryClientExtensions
{
public static IOperationHolder<TrackEventOperation> StartEventOperation(this TelemetryClient client, string eventName)
{
return new TrackEventOperationHolder(eventName, client);
}
}
public class TrackEventOperationHolder : IOperationHolder<TrackEventOperation>
{
private bool _disposed;
private Stopwatch _stopwatch;
private readonly TelemetryClient _client;
public TrackEventOperation Telemetry { get; private set; }
public TrackEventOperationHolder(string eventName, TelemetryClient client)
{
_client = client;
this.Telemetry = new TrackEventOperation(eventName);
_stopwatch = Stopwatch.StartNew();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
try
{
_stopwatch.Stop();
_client.TrackEvent(this.Telemetry.EventName, metrics: new Dictionary<string, double> { { "processingTime", _stopwatch.ElapsedMilliseconds } });
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
}
_disposed = true;
}
}
}
public class TrackEventOperation
{
public string EventName { get; set; }
public TrackEventOperation(string eventName)
{
this.EventName = eventName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment