开发中经常需要log输出调试,但是怎么样看比较合适呢?
package com.tets.util;
import android.util.Log;
/**
* log信息类
* @author Flyjun
*
*/
public class Logger {
private static final String TAG="debug";
//类名
static String className;
//方法名
static String methodName;
//debug行数
static int lineNumber;
/**
* 控制log显示的显示
*/
public static boolean isShowLog=true;
public static void setShowLog(boolean isLog){
isShowLog=isLog;
}
public static void debug(Object msg){
if(!isShowLog){
return;
}
getMethodNames(new Throwable().getStackTrace());
Log.d(TAG ,createLog(msg));
}
public static void debug(String tag,Object msg){
if(!isShowLog){
return;
}
getMethodNames(new Throwable().getStackTrace());
Log.d(tag, createLog(msg));
}
/**
* debug多个参数
* @param args
*
* debugs(new Object[]{"params1",t1},new Object[]{"params2",t2})
*/
public static void debugs(Object[] ... args) {
if(!isShowLog){
return;
}
getMethodNames(new Throwable().getStackTrace());
for (Object[] o:args) { //o[0]表示参数名称 o[1]表示参数值
if(null == o){
Log.d(TAG,createLog("args is null"));
continue;
}
if(o.length >= 2){
if(null == o[1]){
Log.d(TAG,createLog(o[0]+" is null"));
}else{
Log.d(TAG,createLog(o[0]+":"+o[1]));
}
}else{
Log.d(TAG,createLog(o[0]));
}
}
}
/**
* 创建log输出信息
* @param log
* @return
*/
private static String createLog(Object log ) {
StringBuffer buffer = new StringBuffer();
buffer.append(className);
buffer.append(": [");
buffer.append(methodName);
buffer.append(":");
buffer.append(lineNumber);
buffer.append("]");
buffer.append(" "+log);
return buffer.toString();
}
/**
* 获取类名等信息
* @param sElements
*/
private static void getMethodNames(StackTraceElement[] sElements){
className = sElements[1].getFileName();
methodName = sElements[1].getMethodName();
lineNumber = sElements[1].getLineNumber();
}
}