Log
Log最佳实践
- 消灭TAG
我们用TAG就是做定位,同时方便过滤无意义的log。那么索性把当前类名作为这样一个TAG的标识。于是,在我们自定义的log类中就用如下代码设置tag:
/**
* @return 当前的类名(simpleName)
*/
private static String getClassName() {
String result;
StackTraceElement thisMethodStack = (new Exception()).getStackTrace()[1];
result = thisMethodStack.getClassName();
int lastIndex = result.lastIndexOf(".");
result = result.substring(lastIndex + 1, result.length());
return result;
}
- 将Log简化
- 在终端能显示当前类名并且增加超链
这个功能其实ide是支持的,只不过我们可以通过一些神奇的方法来做到更好的效果。下面就给出两个可行的方法:
/**
* @return 当前的类名(全名)
*/
private static String getClassName() {
String result;
StackTraceElement thisMethodStack = (new Exception()).getStackTrace()[1];
result = thisMethodStack.getClassName();
return result;
}
/**
* log这个方法就可以显示超链
*/
private static String callMethodAndLine() {
String result = "at ";
StackTraceElement thisMethodStack = (new Exception()).getStackTrace()[1];
result += thisMethodStack.getClassName()+ ".";
result += thisMethodStack.getMethodName();
result += "(" + thisMethodStack.getFileName();
result += ":" + thisMethodStack.getLineNumber() + ") ";
return result;
}
- 让log更加美观
- 让log支持输出object、map、list、array、jsonStr等对象
增加log自动化和强制开关
疑点
(new Exception()).getStackTrace()[1];
new Exception().getStackTrace()[1];
(new Exception()).getStackTrace()[2];