在Android移動開發中,日誌為我們提供了很多便利。但是應用程式發布後又不想讓應用程式輸出日誌資訊,就可以設計一個日誌開關對應用中的日誌做統一的管理。下面這個簡單的日誌類就完成了這樣的功能,有需要的朋友可以參考。
package com.hitech.jni4cppdemo.utils;public class Log { // 應用程式名稱 private static final String TAG = "ResXtrojan"; // 日誌開關 private static boolean switches = false; // 記錄層級 private static int level = android.util.Log.VERBOSE; public static void v(Object log) { if (switches) { if (level <= android.util.Log.VERBOSE) { if (functionName() != null) { android.util.Log.v(TAG, functionName() + log); } else { android.util.Log.v(TAG, log.toString()); } } } } public static void d(Object log) { if (switches) { if (level <= android.util.Log.DEBUG) { if (functionName() != null) { android.util.Log.d(TAG, functionName() + log); } else { android.util.Log.d(TAG, log.toString()); } } } } public static void i(Object log) { if (switches) { if (level <= android.util.Log.INFO) { if (functionName() != null) { android.util.Log.i(TAG, functionName() + log); } else { android.util.Log.i(TAG, log.toString()); } } } } public static void w(Object log) { if (switches) { if (level <= android.util.Log.WARN) { if (functionName() != null) { android.util.Log.w(TAG, functionName() + log); } else { android.util.Log.w(TAG, log.toString()); } } } } public static void e(Object log) { if (switches) { if (level <= android.util.Log.ERROR) { if (functionName() != null) { android.util.Log.e(TAG, functionName() + log); } else { android.util.Log.e(TAG, log.toString()); } } } } private static String functionName() { StackTraceElement[] sts = Thread.currentThread().getStackTrace(); if (sts == null) { return null; } for (StackTraceElement st : sts) { if (st.isNativeMethod()) { continue; } if (st.getClassName().equals(Thread.class.getName())) { continue; } if (st.getClassName().equals(Log.class.getName())) { continue; } return "at " + st.getFileName() + ", line " + st.getLineNumber() + ", method:" + st.getMethodName() + ", "; // return "Thread:" + Thread.currentThread().getName() + "; Source:" // + st.getFileName() + "\nAt line:" + st.getLineNumber() // + "; Method:" + st.getMethodName(); } return null; }}