Android 打印日志之com.orhanobut.logger的开源库

时间:2022-05-09 15:40:03

查找资料发现github上有不少关于打印日志的的开源库,之后综合考虑使用com.orhanobut.logger的开源库。


一、主要功能:

1、线程信息 Thread information

2、类信息 Class infomation

3、方法信息 Method information

4、打印json内容 pretty-print for json content

5、清除输出Clean output

6、跳到源码 jump to source feature


二、配置

开源地址:https://github.com/orhanobut/logger

在build.gradle中引入Logger:

compile 'com.orhanobut:logger:1.15'


三、使用

可以直接在代码中使用Logger打印日志。而且Tag不是必需的。该类也提供了v,d,i,w,e等方法。如:

LogUtil.d("Hello World");
LogUtil.e("Hello World");
LogUtil.i("Hello World");
LogUtil.v("Hello World");
LogUtil.w("Hello World");


Android 打印日志之com.orhanobut.logger的开源库

该 工具还可以用于打印错误及字符串格式的xml、json等。


四、个性设置

1、当我们输出不带Tag时,默认Tag是tag默认为PRETTYLOGGER,然后即使我们加上了Tag,也只是在PRETTYLOGGER后拼接上Tag,然而我们也可以自定义PRETTYLOGGER,代码如下:

Logger.init("LttAndroid")

注意:要在继承Application的类中写,以应用于全局。


2、隐藏线程信息,可以减少一行显示。

Logger.hideThreadInfo()


3、显示它被使用时所在的方法数量

 
 
Logger.methodCount(3)

因为它支持链式初始化,所以以上三项还可以写成:

Logger.init("LttAndroid").methodCount(2).hideThreadInfo(); 


五、集成


import com.orhanobut.logger.Logger;

/**
* 日志打印工具类
*
* @author Ltt
*
*/
public class LogUtil {
/**
*
* 注意:打包的时候记得设置isDebugfalse
*/
public static boolean isDebug= true;

public static void e(String tag,String msg){
if(isDebug){
Logger.t(tag).e(msg+"");
}
}

public static void d(String tag,String msg){
if(isDebug){
Logger.t(tag).d( msg+"");
}
}

public static void i(String tag,String msg){
if(isDebug){
Logger.t(tag).i( msg+"");
}
}
public static void v(String tag,String msg){
if(isDebug){
Logger.t(tag).v( msg+"");
}
}
public static void w(String tag,String msg){
if(isDebug){
Logger.t(tag).w( msg+"");
}
}
public static void e(String msg){
if(isDebug){
Logger.e(msg+"");
}
}

public static void d(String msg){
if(isDebug){
Logger.d( msg+"");
}
}

public static void i(String msg){
if(isDebug){
Logger.i( msg+"");
}
}
public static void v(String msg){
if(isDebug){
Logger.v( msg+"");
}
}
public static void w(String msg){
if(isDebug){
Logger.w( msg+"");
}
}
public static void json(String json){
if(isDebug){
Logger.json( json);
}
}
public static void xml(String xml){
if(isDebug){
Logger.xml(xml);
}
}
public static void wtf(String wtf){
if(isDebug){
Logger.wtf(wtf);
}
}
}


最后有一篇源码分析的文章,个人感觉有点启发:http://blog.csdn.net/chenantao_gg/article/details/50597103