1. 简介
调用Log记录日志时,如果每个文件定义自己的TAG,且作为Log的第一个入参,那么在adb logcat的使用,要写上多个TAG:d。为了简化,可以让整个应用使用一个TAG,比如使用appName。然后每个class再定义二级TAG,用以界定LOG所在的文件。
2. 实现代码
如下:
package com.example.utils;
import android.util.Log;
public class LogUtils {
private static final String TAG = "MyAppName";
public static void v(String tag, String msg) {
Log.v(TAG, "[" + tag + "]" + msg);
}
public static void v(String tag, String msg, Throwable tr) {
Log.v(TAG, "[" + tag + "]" + msg, tr);
}
public static void d(String tag, String msg) {
Log.d(TAG, "[" + tag + "]" + msg);
}
public static void d(String tag, String msg, Throwable tr) {
Log.d(TAG, "[" + tag + "]" + msg, tr);
}
public static void w(String tag, String msg) {
Log.w(TAG, "[" + tag + "]" + msg);
}
public static void w(String tag, String msg, Throwable tr) {
Log.w(TAG, "[" + tag + "]" + msg, tr);
}
public static void e(String tag, String msg) {
Log.e(TAG, "[" + tag + "]" + msg);
}
public static void e(String tag, String msg, Throwable tr) {
Log.e(TAG, "[" + tag + "]" + msg, tr);
}
public static void printStackTraces(String tag) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
LogUtils.e(TAG, "[" + tag + "] stack trace elements:");
final String TABS = " ";
for (StackTraceElement element : elements) {
Log.e(TAG, TABS + element.toString());
}
}
}
3. 效果示例
06-09 20:05:41.776: D/HelloIntent(1265): [CallerActivity]onCreate()
06-09 20:05:41.886: D/HelloIntent(1265): [CallerActivity]onCreateOptionsMenu()
06-09 20:05:45.056: D/HelloIntent(1265): [CallerActivity]onClick()
06-09 20:05:45.076: D/HelloIntent(1265): [CalleeActivity]onCreate()
06-09 20:05:45.096: D/HelloIntent(1265): [CalleeActivity]intent=Intent { flg=0x20000000 cmp=com.example.hellotoast/com.example.hellointent.CalleeActivity (has extras) }
06-09 20:05:45.096: D/HelloIntent(1265): [CalleeActivity]extra:Hello, Callee!
06-09 20:05:58.446: D/HelloIntent(1265): [CalleeActivity]onClick()
06-09 20:05:58.876: D/HelloIntent(1265): [CalleeActivity]onDestroy()