Skip to content

Instantly share code, notes, and snippets.

@ntxinh
Created June 11, 2020 08:00
Show Gist options
  • Save ntxinh/40ee63ba9216a3a3f528dfbef9b6a9ef to your computer and use it in GitHub Desktop.
Save ntxinh/40ee63ba9216a3a3f528dfbef9b6a9ef to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.ApplicationInsights;
namespace Infrastructure.Services
{
public class AppInsightService : IAppInsightService
{
private TelemetryClient _telemetry;
private Stopwatch _stopwatch;
public AppInsightService(TelemetryClient telemetry)
{
_telemetry = telemetry;
_stopwatch = new Stopwatch();
}
public void TimingStart()
{
if (_stopwatch == null) _stopwatch = new Stopwatch();
_stopwatch.Restart();
}
private void TimingStop()
{
if (_stopwatch == null) return;
_stopwatch.Stop();
}
private void TrackEvent(string eventName, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
_telemetry.TrackEvent(eventName, properties, metrics);
}
private void TrackException(Exception exception, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
_telemetry.TrackException(exception, properties, metrics);
}
public void TrackEvent(string eventName, IDictionary<string, string> properties = null, bool includeMetric = false)
{
Dictionary<string, double> metrics = null;
if (includeMetric && _stopwatch != null)
{
TimingStop();
metrics = new Dictionary<string, double>();
metrics.Add("PROCESSING_TIME", _stopwatch.Elapsed.TotalMilliseconds);
}
TrackEvent(eventName, properties, metrics);
}
public void TrackException(Exception exception, IDictionary<string, string> properties = null, bool includeMetric = false)
{
Dictionary<string, double> metrics = null;
if (includeMetric)
{
TimingStop();
metrics = new Dictionary<string, double>();
metrics.Add("PROCESSING_TIME", _stopwatch.Elapsed.TotalMilliseconds);
}
TrackException(exception, properties, metrics);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment