在android开发中,logcat日志是最常用的打印调试功能。但是android提供的logcat类只能打印TAG信息以及content,因此,受C语言宏定义__FILE__以及__FUNCTION__的启发,优化logcat日志输出。
import android.util.Log;
public class LogcatUtils {
private static final String TAG = "TAG";
public static final int VERBOSE = 1;
public static final int DEBUG = 2;
public static final int INFO = 3;
public static final int WARN = 4;
public static final int ERROR = 5;
public static int LEVEL = ERROR;
public static final String SEPARATOR = " -> ";
public static boolean isDebug = true;
public static void v(String message) {
if (LEVEL >= VERBOSE && isDebug)
Log.v(TAG, getLogInfo() + message);
}
public static void d(String message) {
if (LEVEL >= DEBUG && isDebug)
Log.d(TAG, getLogInfo() + message);
}
public static void i(String message) {
if (LEVEL >= INFO && isDebug)
Log.i(TAG, getLogInfo() + message);
}
public static void w(String message) {
if (LEVEL >= WARN && isDebug)
Log.w(TAG, getLogInfo() + message);
}
public static void e(String message) {
if (LEVEL >= ERROR && isDebug)
Log.e(TAG, getLogInfo() + message);
}
/**
* 输出日志所包含的信息
*/
private static String getLogInfo() {
StackTraceElement traceElement = ((new Exception()).getStackTrace())[2];
StringBuffer toStringBuffer = new StringBuffer().append("[").append(traceElement.getFileName())
.append("-> Method:").append(traceElement.getMethodName()).append(" -> Line:")
.append(traceElement.getLineNumber()).append("]");
return toStringBuffer.toString();
}
}