log Throwable - Android App

Android examples for App:Log

Description

log Throwable

Demo Code


//package com.java2s;
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;
        }//from ww  w .j  a va 2s . c  o m

        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()
                    + ")");
        }

        // recursive call if it has cause
        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();
    }
}

Related Tutorials