简体   繁体   English

应用崩溃时读取和写入错误日志

[英]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/ 参考: http : //schimpf.es/catch-uncaught-exceptions-to-avoid-app-crash/

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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