/**
* 获取打印信息所在方法名,行号等信息
* @return
*/
private static String[] getAutoJumpLogInfos() {
String[] infos = new String[] { "", "", "" };
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
if (elements.length < 5) {
Log.e("MyLogger", "Stack is too shallow!!!");
return infos;
} else {
infos[0] = elements[4].getClassName().substring(
elements[4].getClassName().lastIndexOf(".") + 1);
infos[1] = elements[4].getMethodName() + "()";
infos[2] = " at (" + elements[4].getClassName() + ".java:"
+ elements[4].getLineNumber() + ")";
return infos;
}
}
自定义Log:
public static void v(String msg){
if (DEBUG){
String[] infos = getAutoJumpLogInfos();
android.util.Log.v(infos[0], msg + " : " + infos[1] + infos[2]);
}else{
//donothing
}
}
public static void d(String msg){
if (DEBUG){
String[] infos = getAutoJumpLogInfos();
android.util.Log.d(infos[0], msg + " : " + infos[1] + infos[2]);
}else{
//donothing
}
}
public static void i(String msg){
if (DEBUG){
String[] infos = getAutoJumpLogInfos();
android.util.Log.i(infos[0], msg + " : " + infos[1] + infos[2]);
}else{
//donothing
}
}
public static void w(String msg){
if (DEBUG){
String[] infos = getAutoJumpLogInfos();
android.util.Log.w(infos[0], msg + " : " + infos[1] + infos[2]);
}else{
//donothing
}
}
public static void e(String msg){
if (DEBUG){
String[] infos = getAutoJumpLogInfos();
android.util.Log.e(infos[0], msg + " : " + infos[1] + infos[2]);
}else{
//donothing
}
}
本文介绍了一种在Android中自定义Log打印的方法,通过获取调用堆栈信息,自动记录打印信息的位置,包括方法名和行号,增强了日志的可读性和定位问题的能力。
2020

被折叠的 条评论
为什么被折叠?



