Logging Xamarin unhandled (Android uncaught) exceptions

4.1k Views Asked by At

I'd like to log unhandled exceptions, but I am seeing conflicting information on if and how this may be possible.

I understand that Xamarin raises an AndroidEnvironment.UnhandledExceptionRaiser or AppDomain.CurrentDomain.UnhandledException event and that I can subscribe to this event, but I am under the impression that Android is killing my process and that I don't have access to Android.Utils.Log or the file system.

If you take a look at Xamarin's AdvancedAppLifecycleDemos/HandlingCrashes/App.cs there's a compelling argument that you can't log this exception.

    /// <summary>
    /// When app-wide unhandled exceptions are hit, this will handle them. Be aware however, that typically
    /// android will be destroying the process, so there's not a lot you can do on the android side of things,
    /// but your xamarin code should still be able to work. so if you have a custom err logging manager or 
    /// something, you can call that here. You _won't_ be able to call Android.Util.Log, because Dalvik
    /// will destroy the java side of the process.
    /// </summary>
    protected void HandleUnhandledException(object sender, UnhandledExceptionEventArgs args)
    {
        Exception e = (Exception)args.ExceptionObject;

        // log won't be available, because dalvik is destroying the process
        //Log.Debug (logTag, "MyHandler caught : " + e.Message);
        // instead, your err handling code shoudl be run:
        Console.WriteLine("========= MyHandler caught : " + e.Message);
    }

So how can an unhandled exception be logged?

2

There are 2 best solutions below

0
On BEST ANSWER

Xamarin Insights, HockeyApp or other crash loggers save crash data somehow before the app finishes the process. They send data to the server once the app gets restarted (they cannot send it right away as the process is being killed). So that´s totally possible. Though I´m not sure if they save crash data to device storage (most probably) or to a local SQLite database.

This the code HockeyApp uses to catch unhandled exceptions. It could give you some ideas:

AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) =>
{
    TraceWriter.WriteTrace(args.Exception);
    args.Handled = true;
};

AppDomain.CurrentDomain.UnhandledException += (sender, args) => 
    TraceWriter.WriteTrace(args.ExceptionObject);

// Wire up the unobserved task exception handler
TaskScheduler.UnobservedTaskException +=  (sender, args) =>
    TraceWriter.WriteTrace(args.Exception);

I would suggest to try and write a text file to the local storage within any of those methods

0
On

Xamarin Insights is what you need: https://xamarin.com/insights

With Xamarin Insights you can see a complete overview of any crashes and identify what type of issues and warnings that are occurring in your app

When Xamarin Studio 5.10 final version is released Insights will be integrated also (Read More).