项目开发过程中,打印的log可谓是多而杂,因此对全局log的管理是必不可少。
直接上代码:
import android.util.Log;
/**
* 全局Log管理类
*
* 通过设置 APP_LOG_LEVEL 字段,来控制对应的log是否显示
*/
public class LogHelper {
/**
* 所有log都打印
*/
private static final int LOG_ALL = 0;
/**
* 表达开发调试过程中的一些详细信息。用Log.v()输出,基本不需要关注
*/
private static final int LOG_LEVEL_VERBOSE = 1;
/**
* 表达调试信息。用Log.d()输出
*/
private static final int LOG_LEVEL_DEBUG = 2;
/**
* 表达一些信息。用Log.i()输出
*/
private static final int LOG_LEVEL_INFO = 3;
/**
* 表示警告,可能会引起错误,开发时有时用来表示特别注意的地方。用Log.w()输出
*/
private static final int LOG_LEVEL_WARN = 4;
/**
* 表示错误,是需要解决的。用Log.e()输出
*/
private static final int LOG_LEVEL_ERROR = 5;
/**
* 所有log都不打印
*/
private static final int LOG_NONE = 6;
//定义log的级别,数值越大,级别越高
private static int APP_LOG_LEVEL = LOG_NONE;
public static void v(String tag, Object... messages){
log(tag,LOG_LEVEL_VERBOSE,messages);
}
public static void d(String tag, Object... messages){
log(tag,LOG_LEVEL_DEBUG,messages);
}
public static void i(String tag, Object... messages){
log(tag,LOG_LEVEL_INFO,messages);
}
public static void w(String tag, Object... messages){
log(tag,LOG_LEVEL_WARN,messages);
}
public static void e(String tag, Object... messages){
log(tag,LOG_LEVEL_ERROR,messages);
}
private static void log(String tag, int level, Object... messages) {
if (level<APP_LOG_LEVEL){
return;
}
String message;
if (messages != null && messages.length == 1) {
// handle this common case without the extra cost of creating a StringBuffer:
message = messages[0].toString();
} else {
StringBuilder sb = new StringBuilder();
if (messages != null) for (Object m : messages) {
sb.append(m).append("\n");
}
message = sb.toString();
}
Log.println(level, tag, message);
}
}
根据项目的log打印需求,通过控制APP_LOG_LEVEL字段,像开关一样,方便的对全局log进行统一管理。比如,上线前需要将所有log关闭,直接将APP_LOG_LEVEL置为LOG_NONE即可。