1. 程式人生 > >Logger-功能強大使用方便的Log日誌列印工具類

Logger-功能強大使用方便的Log日誌列印工具類

介紹

Android開發中Log日誌列印對開發者來說是非常重要的功能。但是感覺Log寫多了也是煩,每次都需要設定一個TAG過濾值和具體的列印資訊,而且列印的資訊也不夠豐富。
這裡我推薦一個功能強大的Log日誌列印工具類-Logger。(不是java.util.logging.Logger,只是恰好同名而已)

使用

使用非常簡單,直接呼叫靜態類方法。提供Debug/Info/Error三個級別的列印方法。每個方法又分為兩種,有引數和空參的兩種。

        Logger.d();
        Logger.d("log message");

使用效果

有圖為證。列印效果,格式說明。
預設TAG: [ 執行類:呼叫的方法:程式碼行數 ] :列印資訊
列印效果


打出的資訊非常豐富,有方法和程式碼行數。方便我們定位程式碼。還可以在版本釋出後,統一關閉日誌列印功能。很好的滿足了我們的開發日誌列印功能。

原始碼及說明

程式碼說明

  • TAG在工具類中設定好,每個App專案都有特定的TAG。
  • 設計3個布林值,作為用來控制列印的開關,預設ture。在版本釋出後改為false就好了。
  • 每個列印,都有兩個過載方法,有參無參,根據實際情況使用。
  • 最後getLocation方法,獲取堆疊資訊,提供列印方法和程式碼行功能。

原始碼

public final class Logger {

    private static final String TAG = "Demo"
; /** * Set true or false if you want read logs or not */ private static boolean logEnabled_d = true; private static boolean logEnabled_i = true; private static boolean logEnabled_e = true; public static void d() { if (logEnabled_d) { android.util.Log.d(TAG, getLocation()); } } public
static void d(String msg) { if (logEnabled_d) { android.util.Log.d(TAG, getLocation() + msg); } } public static void i(String msg) { if (logEnabled_i) { android.util.Log.i(TAG, getLocation() + msg); } } public static void i() { if (logEnabled_i) { android.util.Log.i(TAG, getLocation()); } } public static void e(String msg) { if (logEnabled_e) { android.util.Log.e(TAG, getLocation() + msg); } } public static void e(String msg, Throwable e) { if (logEnabled_e) { android.util.Log.e(TAG, getLocation() + msg, e); } } public static void e(Throwable e) { if (logEnabled_e) { android.util.Log.e(TAG, getLocation(), e); } } public static void e() { if (logEnabled_e) { android.util.Log.e(TAG, getLocation()); } } private static String getLocation() { final String className = Logger.class.getName(); final StackTraceElement[] traces = Thread.currentThread() .getStackTrace(); boolean found = false; for (StackTraceElement trace : traces) { try { if (found) { if (!trace.getClassName().startsWith(className)) { Class<?> clazz = Class.forName(trace.getClassName()); return "[" + getClassName(clazz) + ":" + trace.getMethodName() + ":" + trace.getLineNumber() + "]: "; } } else if (trace.getClassName().startsWith(className)) { found = true; } } catch (ClassNotFoundException ignored) { } } return "[]: "; } private static String getClassName(Class<?> clazz) { if (clazz != null) { if (!TextUtils.isEmpty(clazz.getSimpleName())) { return clazz.getSimpleName(); } return getClassName(clazz.getEnclosingClass()); } return ""; } }

來源

其實這也不是我寫的,只是在開發的時候發現了,分享出來。
程式碼來源是:Yalantis公司的開源專案中的工具類。
Yalantis公司有很多效果非常酷炫的開源專案,大家可以上github上看看。