Created
December 21, 2016 15:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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