1. 程式人生 > >Android列印工具類

Android列印工具類

    Android列印除錯類,可打印出日誌所在的檔名、方法名、行號,使用的時候將Log換成LogTools即可,其他地方不變。
public class LogTools {
    private static final String DEBUG_TAG = "TEST";
    public static void v(String tag, String msg){
        Log.v(tag, LogTools.appendExtraStr(msg));
    }

    public static void i(String tag, String msg){
        Log.i(tag, LogTools.appendExtraStr(msg));
    }

    public static void d(String tag, String msg){
        Log.d(tag, LogTools.appendExtraStr(msg));
    }

    public static void w(String tag, String msg){
        Log.w(tag, LogTools.appendExtraStr(msg));
    }

    public static void e(String tag, String msg){
        Log.e(tag, LogTools.appendExtraStr(msg));
    }

    private static String appendExtraStr(String msg){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(msg).append("   [").append(LogTools._FUNC_()).append("; ").append(LogTools._FILE_()).append(":").append(LogTools._LINE_()).append("]");

        return stringBuilder.toString();
    }

//當前檔名
    private static String _FILE_() {
        StackTraceElement traceElement = ((new Exception()).getStackTrace())[3];
        return traceElement.getFileName();
    }

    // 當前方法名
    private static String _FUNC_() {
        StackTraceElement traceElement = ((new Exception()).getStackTrace())[3];
        return traceElement.getMethodName();
    }

    // 當前行號
    private static int _LINE_() {
        StackTraceElement traceElement = ((new Exception()).getStackTrace())[3];
        return traceElement.getLineNumber();
    }
}

//呼叫堆疊
    public static void printCallStatck() {
        Throwable ex = new Throwable();
        StackTraceElement[] stackElements = ex.getStackTrace();
        StringBuilder logoutBuilder = new StringBuilder();

        if (stackElements != null) {
        	logoutBuilder.append("---------------------------------------------");
            for (int i = 0; i < stackElements.length; i++) {
            	logoutBuilder.append(stackElements[i].getClassName()+"/");
            	logoutBuilder.append(stackElements[i].getFileName()+"/");
            	logoutBuilder.append(stackElements[i].getLineNumber()+"/");
            	logoutBuilder.append(stackElements[i].getMethodName()+"\r\n");
            }
            logoutBuilder.append("---------------------------------------------");
        }
        LogTools.d(DEBUG_TAG, logoutBuilder.toString());
    }