統一日誌輸出格式,自動附帶類名、方法名、行號、線程信息,支持關閉開關,提供 v/d/i/w/e/wtf 六級別,兼容 Android Log 與標準輸出。
Throwable.getStackTrace()[0] 獲取調用點行號、類名、方法名setIsShowLog(false) 生產環境一鍵關閉public final class LogUtils {
private static final String TAG = "Jenly";
private static final String COLON = ":", ARROW = "->";
private static boolean isShowLog = true;
public static void setIsShowLog(boolean b) { isShowLog = b; }
// 核心構建消息方法
private static String buildMsg(Throwable e, String msg) {
StackTraceElement ste = e.getStackTrace()[0];
return new StringBuilder()
.append(ste.getLineNumber()).append(COLON)
.append(ste.getClassName()).append(ARROW)
.append(ste.getMethodName()).append(COLON)
.append(msg).toString();
}
// v 級別示例,其他級別同理
public static void v(String msg) { if (isShowLog) Log.v(TAG, msg); }
public static void v(String tag, String msg) { if (isShowLog) Log.v(tag, msg); }
public static void v(Class<?> cls, String msg) {
if (isShowLog) Log.v(TAG, cls.getSimpleName() + COLON + msg);
}
public static void v(Throwable e) { if (isShowLog) v(TAG, e); }
public static void v(String tag, Throwable e) {
if (isShowLog) Log.v(tag, buildMsg(e, e.getMessage()));
}
public static void v(Throwable e, String msg) { if (isShowLog) v(TAG, e, msg); }
public static void v(String tag, Throwable e, String msg) {
if (isShowLog) Log.v(tag, buildMsg(e, msg));
}
// d/i/w/e/wtf 同理...
// System.out 封裝
public static void print(String msg) { if (isShowLog) System.out.print(msg); }
public static void println(String msg) { if (isShowLog) System.out.println(msg); }
}
// 普通日誌
LogUtils.d("UserService", "User login: " + userId);
// 異常日誌(自動帶行號類名方法)
try { risky(); }
catch (Exception e) { LogUtils.e(e, "Login failed"); }
// 關鍵業務點標記
LogUtils.i(OrderService.class, "Order created: " + orderId);
// 生產環境關閉
LogUtils.setIsShowLog(BuildConfig.DEBUG);
D/Jenly: 42:com.example.UserService->login:User login: 1001
E/Jenly: 15:com.example.OrderService->create:Order created: 2023
W/System.err: java.lang.NullPointerException
at com.example.Risky.risky(Risky.java:10)
| 框架 | 優點 | 適用場景 |
|---|---|---|
| LogUtils (本工具) | 零依賴、輕量、Android 友好 | 中小項目、快速原型 |
| SLF4J + Logback | 標準門面、性能強、功能全 | 服務端、企業級應用 |
| Log4j2 | 異步日誌、GC-free、插件化 | 高吞吐、低延遲系統 |
| Android Log | 系統集成、logcat 過濾 | Android App 必備 |