Android開發(fā)中硬霍,調(diào)試程序時(shí)會(huì)打印log抠蚣,當(dāng)log足夠多的時(shí)候切厘,想要找到打印log的位置就比較麻煩,不得已還得全文搜索菲茬。接下來介紹一個(gè)便捷的方式定位到log的位置
打印的log可以直接鏈接回代碼
使用方式
Logger.e("測(cè)試一下");
效果圖
工具類完整代碼
import android.util.Log;
/**
* 日志類:可以鏈接回代碼
*/
public class Logger {
protected static final String TAG = "WADAXI";
private Logger() {
}
public static void v(String msg) {
if (BuildConfig.DEBUG) {
Log.v(TAG, buildMessage(msg));
}
}
public static void v(String msg, Throwable t) {
if (BuildConfig.DEBUG) {
Log.v(TAG, buildMessage(msg), t);
}
}
public static void d(String msg) {
if (BuildConfig.DEBUG) {
Log.d(TAG, buildMessage(msg));
}
}
public static void d(String msg, Throwable t) {
if (BuildConfig.DEBUG) {
Log.d(TAG, buildMessage(msg), t);
}
}
public static void i(String msg) {
if (BuildConfig.DEBUG) {
Log.i(TAG, buildMessage(msg));
}
}
public static void i(String msg, Throwable t) {
if (BuildConfig.DEBUG) {
Log.i(TAG, buildMessage(msg), t);
}
}
public static void w(String msg) {
if (BuildConfig.DEBUG) {
Log.w(TAG, buildMessage(msg));
}
}
public static void w(String msg, Throwable t) {
if (BuildConfig.DEBUG) {
Log.w(TAG, buildMessage(msg), t);
}
}
public static void e(String msg) {
if (BuildConfig.DEBUG) {
Log.e(TAG, buildMessage(msg));
}
}
public static void e(String msg, Throwable t) {
if (BuildConfig.DEBUG) {
Log.e(TAG, buildMessage(msg), t);
}
}
/**
* 構(gòu)建 log 的 message
*
* @param message 要打印的信息
* @return 完成拼接的信息
*/
private static String buildMessage(String message) {
StackTraceElement stackTrace = new Throwable().fillInStackTrace().getStackTrace()[2];
String fullName = stackTrace.getClassName();
StringBuilder builder = new StringBuilder();
builder.append(message).append("{(");
if (fullName.contains("$")) {
builder.append(fullName.substring(fullName.lastIndexOf(".") + 1, fullName.indexOf("$")));
} else {
builder.append(fullName.substring(fullName.lastIndexOf(".") + 1));
}
builder.append(".java:")
.append(stackTrace.getLineNumber())
.append(")#")
.append(stackTrace.getMethodName())
.append("()}");
return builder.toString();
}
}
當(dāng)然,這個(gè)TAG可以自定義吓笙,你也可以任意改造這個(gè)工具類映屋。
只是為了讓log更便捷