Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging Xamarin unhandled (Android uncaught) exceptions

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?

like image 766
Adam Avatar asked Jun 11 '15 15:06

Adam


1 Answers

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

like image 91
xleon Avatar answered Sep 27 '22 20:09

xleon