Logging with Xamarin Insights (but not on Unified App)
I've been using Xamarin Insights to track exceptions in a mobile application recently. It's great, but unfortunately it doesn't yet work on Xamarin iOS Unified applications. I also wanted to be able to easily turn Insights on and off and to see in the debug log everything that was being sent (other than app crashes which are beyond the reach of C# code).
So I created this simple wrapper that doesn't rely on Insights being present or initialized in the host (iOS or Android) application. The API follows the Insights API for the most part except I chose not to expose the `ReportSeverity` enum because the iOS Unified app depends on the PCL shared project. (The Insights package had to be removed from the Unified app until a compatible version is available).
Feel free to use it if it helps.
using System;
using Xamarin;
using System.Collections.Generic;
using System.Diagnostics;
using Xamarin.Forms;
namespace Mobile
{
///<summary>
/// Methods to write to debug log and to Insights
///</summary>
public class Logger
{
public static void Identify(string uid, IDictionary\<string, string\> table)
{
System.Diagnostics.Debug.WriteLine ("Identifying : " + uid);
if (Insights.IsInitialized) { Insights.Identify(uid, table); }
}
public static void Debug(string message)
{
System.Diagnostics.Debug.WriteLine (message);
}
public static void Report (string message)
{
System.Diagnostics.Debug.WriteLine (message);
if (Insights.IsInitialized) { Insights.Track (message); }
}
public static void Warning (Exception ex)
{
System.Diagnostics.Debug.WriteLine (ex.ToString());
if (Insights.IsInitialized) { Insights.Report (ex, ReportSeverity.Warning); }
}
public static void Error (Exception ex)
{
System.Diagnostics.Debug.WriteLine (ex.ToString());
if (Insights.IsInitialized) { Insights.Report (ex, ReportSeverity.Error); }
}
public static IDisposable TrackTime(string message, IDictionary<string,string> table = null)
{
return new DisposableTimer (message, table);
}
private class DisposableTimer : IDisposable
{
Stopwatch sw;
private readonly string identifier;
private readonly ITrackHandle trackHandle;
public DisposableTimer(string identifier, IDictionary<string, string> table)
{
this.identifier = identifier;
sw = Stopwatch.StartNew();
if (Insights.IsInitialized)
{
this.trackHandle = Insights.TrackTime(identifier, table);
this.trackHandle.Start(); // Would be nice if there was a StartNew()
}
System.Diagnostics.Debug.WriteLine("Starting " + identifier);
}
bool disposed = false;
public void Dispose ()
{
if (!disposed)
{
sw.Stop ();
disposed = true;
if (this.trackHandle != null)
{
this.trackHandle.Stop ();
this.trackHandle.Dispose ();
}
System.Diagnostics.Debug.WriteLine ("Finished " + this.identifier + " took " + sw.ElapsedMilliseconds + "ms");
}
}
}
}
}