1. 程式人生 > >捕捉系統崩潰日誌 並且儲存到本地

捕捉系統崩潰日誌 並且儲存到本地


import android.content.Context;

import java.io.File;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.io.Writer;


/**
 * @param
 * @Comments : 捕捉系統崩潰日誌
 * @Author : Lampo
 * @ModifiedBy : Lampo
 * @Modified :
 */

public class ExceptionLogUtil implements Thread.UncaughtExceptionHandler {

    private Thread.UncaughtExceptionHandler mUncaught = null;
    private static ExceptionLogUtil exceptionLog = null;
    private static String PATH_LOGCAT;
    private File logFile;

    public static ExceptionLogUtil getInstance() {
        if (exceptionLog == null) {
            exceptionLog = new ExceptionLogUtil();
        }
        return exceptionLog;
    }

    public void init(Context context) {
        PATH_LOGCAT = FileUtils.CreateFiles(context, "ErrorLog");
        FileUtils.deleteExceedOneMonth(PATH_LOGCAT);
        try {
            if (mUncaught == null) {
                mUncaught = Thread.getDefaultUncaughtExceptionHandler();
                Thread.setDefaultUncaughtExceptionHandler(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        if (!handleException(throwable) && mUncaught != null) {
            mUncaught.uncaughtException(thread, throwable);
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    private boolean handleException(Throwable ex) {
        try {
            if (ex == null)
                return false;
            save(ex);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void save(Throwable ex) {
        try {
            logFile = FileUtils.createNewLogFile(PATH_LOGCAT);
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            ex.printStackTrace(printWriter);
            printWriter.close();

            RandomAccessFile raf = new RandomAccessFile(logFile, "rwd");
            raf.seek(logFile.length());
            raf.write((Util.getNowDate_All() +"----------------\r\n" + writer.toString() + "\r\n").getBytes());
            raf.close();
            PDALogger.e(writer.toString());
        } catch (Exception e) {
            e.printStackTrace();
            PDALogger.e(e.toString());
        }
    }
}


/**
     * 在Cit資料夾下建立新的子資料夾
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String CreateFiles(Context context, String fileName) {
        String PATH_LOGCAT;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 優先儲存到SD卡中
            PATH_LOGCAT = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Config.APP_NAME + "/" + fileName;
        } else {// 如果SD卡不存在,就儲存到本應用的目錄下
            PATH_LOGCAT = context.getFilesDir().getAbsolutePath() + File.separator + Config.APP_NAME + "/" + fileName;
        }
        File file = new File(PATH_LOGCAT);
        if (!file.exists()) {
            file.mkdirs();
        }
        return PATH_LOGCAT;
    }




    /**
     * 刪除超過一個月的log
     *
     * @param path 資料夾名稱
     */
    public static void deleteExceedOneMonth(String path) {
        File file1 = new File(path);
        File[] files = file1.listFiles();
        if (files.length <= 30) {
            return;
        }
        for (int i = 0; i < files.length; i++) {
            String str = files[i].getName().replace(".log", "").replace("CIT-", "");
            if (str.indexOf("U") != -1) {
                str = str.replace("-U", "");
            }
            if (!Util.isExceedOneMonth(str)) {
                deleteFile(path + "/" + files[i].getName());
            }
        }
    }


 /**
     * 是否是30天內
     *
     * @param month
     * @return
     * @throws ParseException
     */
    public static boolean isExceedOneMonth(String month) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        long day = 0;
        try {
            date = df.parse(month + " 00:00:00");
            long time = date.getTime();
            Date now = df1.parse(getNowDate());
            long nowTime = now.getTime();
            day = (nowTime - time) / (24 * 60 * 60 * 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (day <= 30) {
            return true;
        } else {
            return false;
        }
    }



 /**
     * 單個刪除檔案
     *
     * @param path
     */
    public static void deleteFile(String path) {
        File file = new File(path);
        if (file.exists() && file.isFile()) {//是否可以在該檔案中找到該檔案//該檔案是否表示底層上
            PDALogger.e("file.isFile  true");
            file.delete();
        }
    }