Skip to content

Instantly share code, notes, and snippets.

@uglybugger
Created August 27, 2011 01:16
Show Gist options
  • Save uglybugger/1174826 to your computer and use it in GitHub Desktop.
Save uglybugger/1174826 to your computer and use it in GitHub Desktop.
Crash Logging in a MonoTouch App
public partial class AppDelegate : UIApplicationDelegate
{
private ILogger _logger;
// This method is invoked when the application has loaded its UI and its ready to run
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
window.AddSubview(navigationController.View);
window.MakeKeyAndVisible();
LetThereBeIoC();
_logger = IoCServiceLocator.Resolve<ILogger>();
var crashLog = CrashLog.Read();
if (crashLog != null) _logger.Log("An error caused the application to crash", crashLog);
return true;
}
// ...
}
public static class CrashLog
{
private static readonly string _crashLogPath = "{0}/CrashLog.txt"
.FormatWith(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
public static string Read()
{
if (!File.Exists(_crashLogPath)) return null;
var crashLog = File.ReadAllText(_crashLogPath);
Delete();
return crashLog;
}
public static void Write(string message)
{
Console.WriteLine("Writing crash log...");
Console.WriteLine(message);
File.WriteAllText(_crashLogPath, message);
Console.WriteLine("... done.");
}
public static void Write(Exception exc)
{
var crashLog = "{0}: {1}".FormatWith(exc.Message, exc);
Write(crashLog);
}
public static void Delete()
{
File.Delete(_crashLogPath);
}
}
public class Application
{
private static void Main(string[] args)
{
try
{
UIApplication.Main(args);
}
catch (Exception exc)
{
CrashLog.Write(exc);
// Don't throw here - it crashes MonoDevelop.
// Just exit gracefully.
}
}
}
public class Application
{
private static void Main(string[] args)
{
UIApplication.Main(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment