安卓(Android) 怎么实现日志记录 Throwable

2019年10月19日11:03:28安卓(Android) 怎么实现日志记录 Throwable已关闭评论 850 1520字阅读5分4秒

1.简介

安卓(Android) 怎么实现日志记录 Throwable?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    private static final int LOG_SIZE = 1024 * 512;
    private static String sLogPath;
    private static String slogFile = "Log.txt";
    private static SimpleDateFormat sDateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    public static void logThrowable(Throwable t) {
        if (t == null) {
            return;
        }

        logToFile("Exception: " + t.getClass().getName());
        logToFile("Message: " + t.getMessage());
        StackTraceElement[] array = t.getStackTrace();
        for (StackTraceElement ste : array) {
            logToFile("  " + ste.getClassName() + "." + ste.getMethodName()
                    + "(" + ste.getFileName() + ":" + ste.getLineNumber()
                    + ")");
        }

        
        logThrowable(t.getCause());
    }

    public static void logToFile(String content) {
        Date nowtime = new Date();
        String needWriteMessage = sDateFormat.format(nowtime) + ":"
                + content;

        try {
            File file = new File(sLogPath, slogFile);
            if (!file.exists()) {
                ensurePath(file);
                file.createNewFile();
            }

            FileWriter filerWriter = new FileWriter(file, true);
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
            bufWriter.write(needWriteMessage);
            bufWriter.newLine();
            bufWriter.close();
            filerWriter.close();

            FileInputStream fis = new FileInputStream(file);
            if (fis.available() > LOG_SIZE) {
                file.delete();
            }
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static synchronized boolean ensurePath(File file) {
        String filePath = file.getParent();
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir.exists();
    }
}

 
继续阅读
编程十万个怎么办