开发中常用到log输出,稍微规范些的项目必然会使用专门的log工具类进行管理。
随着零零星星的进行更改,形成了我现在用的log工具类,代码结构比较简单,功能差不多能满足日常开发需要,现在分享给大家,也希望大伙提出改进。
package com.haier.ota.util;
import android.util.Log;
import com.haier.ota.BuildConfig;
public class LogUtil {
public static boolean showDebugLog = BuildConfig.DEBUG;
public static void i(Object objTag, Object objMsg) {
String tag = getTag(objTag);
String msg = (objMsg == null || objMsg.toString() == null) ? "null" : objMsg.toString();
Log.i(tag, getMsgFormat(msg));
}
public static void d(Object objTag, Object objMsg) {
if (showDebugLog) {
String tag = getTag(objTag);
String msg = (objMsg == null || objMsg.toString() == null) ? "null" : objMsg.toString();
Log.d(tag, getMsgFormat(msg));
}
}
public static void w(Object objTag, Object objMsg) {
String tag = getTag(objTag);
String msg = (objMsg == null || objMsg.toString() == null) ? "null" : objMsg.toString();
Log.w(tag, getMsgFormat(msg));
}
public static void e(Object objTag, Object objMsg) {
String tag = getTag(objTag);
String msg = (objMsg == null || objMsg.toString() == null) ? "null" : objMsg.toString();
Log.e(tag, getMsgFormat(msg));
}
private static String getTag(Object objTag) {
String tag;
if (objTag instanceof String) {
tag = (String) objTag;
} else if (objTag instanceof Class) {
tag = ((Class<?>) objTag).getSimpleName();
} else {
tag = objTag.getClass().getSimpleName();
}
return tag;
}
/**
* 获取类名,方法名,行号
*
* @return Thread:main, at com.haier.ota.OTAApplication.onCreate(OTAApplication.java:35)
*/
private static String getFunctionName() {
try {
StackTraceElement[] sts = Thread.currentThread().getStackTrace();
if (sts != null) {
for (StackTraceElement st : sts) {
if (st.isNativeMethod()) {
continue;
}
if (st.getClassName().equals(Thread.class.getName())) {
continue;
}
if (st.getClassName().equals(LogUtil.class.getName())) {
continue;
}
return "Thread:" + Thread.currentThread().getName() + ", at " + st.getClassName() + "." + st.getMethodName()
+ "(" + st.getFileName() + ":" + st.getLineNumber() + ")";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String getMsgFormat(String msg) {
return msg + "----" + getFunctionName();
}
}
最后,话唠一下,开发中log输出不要太过频繁(即避免短时间内大量输出log),log底层使用的应该是异步机制,频繁输出log很可能会丢失部分log,导致分析log的时候以为代码知悉出现了异常。