1驹止、Logger簡介
Logger相對系統(tǒng)自帶log斋扰,輸出格式清晰鞋怀,功能更全屋休,使用方便
github:https://github.com/orhanobut/logger
2、簡單使用
1)添加依賴
implementation 'com.orhanobut:logger:2.2.0'
2)初始化
Logger.addLogAdapter(new AndroidLogAdapter());
3)使用
Logger.d("hello");
3梆惯、修改默認配置
FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
.showThreadInfo(false) //(可選)是否顯示線程信息酱鸭。 默認值為true
.methodCount(2) // (可選)要顯示的方法行數。 默認2
.methodOffset(7) // (可選)設置調用堆棧的函數偏移值垛吗,0的話則從打印該Log的函數開始輸出堆棧信息凹髓,默認是0
.logStrategy(customLog) //(可選)更改要打印的日志策略。 默認LogCat
.tag("MyTAG") //(可選)每個日志的全局標記怯屉。 默認PRETTY_LOGGER(如上圖)
.build();
Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
一般使用默認配置即可
4蔚舀、設置標簽
1)設置全局標簽,如同修改默認參數一樣
FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
.tag("MyTAG")
.build();
Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
2)設置局部標簽
Logger.t("TAG").d("tag hello");
5蚀之、關閉日志輸出
當 isLoggable 返回true時輸出日志蝗敢,否則不輸出
Logger.addLogAdapter(new AndroidLogAdapter() {
@Override public boolean isLoggable(int priority, String tag) {
return BuildConfig.DEBUG;
}
});
可根據參數 priority、 tag 選擇性的關閉打開日志
6足删、寫日志到文本
寫到日志寿谴,需要寫入權限
AndroidManifest.xml申請,還要在動態(tài)申請
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
開啟寫入配置
CsvFormatStrategy formatStrategy = CsvFormatStrategy.newBuilder()
.tag("custom")
.build();
Logger.addLogAdapter(new DiskLogAdapter(formatStrategy));
從CsvFormatStrategy源碼中看到失受,設置后日志將會寫到根目錄logger文件夾下的文件中
String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String folder = diskPath + File.separatorChar + "logger";
當日志文件超過500K時讶泰,將新建文件
private static final int MAX_BYTES = 500 * 1024; // 500K averages to a 4000 lines per file
7、注意
如果要寫到文件拂到,同時也要在控制臺中看到痪署,需要同時添加兩個適配器
CsvFormatStrategy formatStrategy = CsvFormatStrategy.newBuilder()
.tag("custom")
.build();
Logger.addLogAdapter(new DiskLogAdapter(formatStrategy));
Logger.addLogAdapter(new AndroidLogAdapter()
{
// 是否開啟打印功能,返回true則打印兄旬,否則不打印
@Override
public boolean isLoggable(int priority, String tag)
{
return BuildConfig.DEBUG;
}
});