直接上代码:
import android.os.Environment;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Create a simple and more understandable Android logs.
* 后面就不用在每个类中都写TAG了。
* */
public class DebugLog {
private static final String TAG = "app_name";
static String className;
static String methodName;
static int lineNumber;
private static boolean misdebug = true;
private DebugLog(){
/* Protect from instantiations */
}
public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
return misdebug;
}
// 拼接 方法名+行号+log
private static String createLog(String log ) {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
buffer.append(methodName);
buffer.append(":");
buffer.append(lineNumber);
buffer.append("]");
buffer.append(log);
return buffer.toString();
}
private static void getMethodNames(StackTraceElement[] sElements){
className = sElements[1].getFileName(); //类名
methodName = sElements[1].getMethodName();//方法名
lineNumber = sElements[1].getLineNumber();// 行号
}
public static void e(String message){
if (!isDebuggable())
return;
// Throwable instance must be created before any methods
getMethodNames(new Throwable().getStackTrace());
Log.e(TAG,className+"--"+createLog(message));
}
public static void i(String message){
if (!isDebuggable())
return;
getMethodNames(new Throwable().getStackTrace());
Log.i(TAG,className+"--"+createLog(message));
}
public static void d(String message){
if (!isDebuggable())
return;
getMethodNames(new Throwable().getStackTrace());
Log.d(TAG,className+"--"+createLog(message));
}
public static void v(String message){
if (!isDebuggable())
return;
getMethodNames(new Throwable().getStackTrace());
Log.v(TAG,className+"--"+createLog(message));
}
public static void w(String message){
if (!isDebuggable())
return;
getMethodNames(new Throwable().getStackTrace());
Log.w(TAG,className+"--"+createLog(message));
}
}
用的时候直接调用DebugLog.i(log);然后logcat中就会直接打印出对应的方法名,具体的行号了。