简体   繁体   中英

Read and Write Error Log when app crash

I would like to get Error log details from application when it crashes. Application may have null pointer exception or any thing, when it arises i want to write this in one file.

Created One Exception handler like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Java.IO;
using Android.Util;

namespace errorlogdemo
{
    class ExceptionHandler: Java.Lang.Thread.IUncaughtExceptionHandler
    {
        private Java.Lang.Thread.IUncaughtExceptionHandler defaultUEH;
        private Activity app = null;
        private string localPath;

        public ExceptionHandler(Activity app) {
            this.defaultUEH = Java.Lang.Thread.DefaultUncaughtExceptionHandler;
            this.app = app;
            this.localPath = "/data/data/appname/files";
        }

        private void writeToFile(string stacktrace, string filename) {
            try {
                BufferedWriter bos = new BufferedWriter(new FileWriter(
                    localPath + "/" + filename));
                bos.Write(stacktrace);
                Log.Debug("Handler Error",stacktrace);
                bos.Flush();
                bos.Close();
            } catch (Java.Lang.Exception e) {

                e.PrintStackTrace();
            }
        }

        #region IUncaughtExceptionHandler implementation

        void Thread.IUncaughtExceptionHandler.UncaughtException (Thread thread, Throwable e)
        {
            Writer result = new StringWriter();
            PrintWriter printWriter = new PrintWriter(result);
            e.PrintStackTrace(printWriter);
            string stacktrace = result.ToString();
            printWriter.Close();
            string filename = "log.stacktrace";

            if (localPath != null) {
                writeToFile(stacktrace, filename);
            }
            defaultUEH.UncaughtException(thread, e);
        }

        #endregion
    }
}

Created Instance for this handler from Main Activity:

Java.Lang.Thread.IUncaughtExceptionHandler = new ExceptionHandler (this);

While launching the applciation i have the following

Button button = null;
button.click+=delegate{
};

This will cause app to crash but this time exception handler is not called. Why?

Reference: http://schimpf.es/catch-uncaught-exceptions-to-avoid-app-crash/

如果您处理了异常,则该应用不会崩溃,请创建console log并进行检查。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM