異常處理 - 生成問題記錄日志

/**
 * @author zuo
 * @date 2018/6/20 12:37
 */
public class LogUtil {
    private static final String FILE_NAME = "/logs.txt";
    private static Boolean MYLOG_SWITCH = true; // 日志文件總開關(guān)

    public static void i(String str) {
        if (MYLOG_SWITCH) {
            writeException(str);
        }
    }

    public static void LogException(Exception e) {
        if (MYLOG_SWITCH) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String str = sw.toString();
            writeException(str);
        } else {
            e.printStackTrace();
        }
    }

    private static void writeException(String content) {
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 獲取SD卡的目錄
                File sdCardDir = Environment.getExternalStorageDirectory();
                File targetFile = new File(sdCardDir.getCanonicalPath()
                        + FILE_NAME);
                @SuppressLint("SimpleDateFormat")
                String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
                String logStr = String.format("\n\n%s\n%s", date, content);
                // 以指定文件創(chuàng)建RandomAccessFile對象
                RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
                // 將文件記錄指針移動到最后
                raf.seek(targetFile.length());
                // 輸出文件內(nèi)容
                raf.write(logStr.getBytes());
                raf.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String readException() {
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 獲得SD卡對應(yīng)的存儲目錄
                File sdCardDir = Environment.getExternalStorageDirectory();
                // 獲取指定文件對應(yīng)的輸入流
                FileInputStream fis = new FileInputStream(
                        sdCardDir.getCanonicalPath() + FILE_NAME);
                // 將指定輸入流包裝成BufferReader
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        fis));
                StringBuilder sb = new StringBuilder("");
                String line = null;
                // 循環(huán)讀取文件內(nèi)容
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容