package cn.sinata.rxnetty;
|
|
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.Locale;
|
|
|
/**
|
* author:Created by ZHT on 2020/05/26 22:44
|
* email:526309416@qq.com
|
* desc:
|
*/
|
public class Logger {
|
|
//设为false关闭日志
|
private static final boolean LOG_ENABLE = BuildConfig.DEBUG;
|
//写入文件需要开启权限 日志记录不强行做权限判断
|
private static final boolean SAVE_FILE = false;
|
|
public static void i(String tag, String msg) {
|
if (LOG_ENABLE) {
|
Log.i(tag, msg);
|
if (SAVE_FILE) {
|
writeLogtoFile(tag, msg);
|
}
|
}
|
}
|
|
public static void v(String tag, String msg) {
|
if (LOG_ENABLE) {
|
Log.v(tag, msg);
|
}
|
}
|
|
public static void d(String tag, String msg) {
|
if (LOG_ENABLE) {
|
Log.d(tag, msg);
|
if (SAVE_FILE) {
|
writeLogtoFile(tag, msg);
|
}
|
}
|
}
|
|
public static void w(String tag, String msg) {
|
if (LOG_ENABLE) {
|
Log.w(tag, msg);
|
if (SAVE_FILE) {
|
writeLogtoFile(tag, msg);
|
}
|
}
|
}
|
|
public static void e(String tag, String msg) {
|
if (LOG_ENABLE) {
|
Log.e(tag, msg);
|
if (SAVE_FILE) {
|
writeLogtoFile(tag, msg);
|
}
|
}
|
}
|
|
/**
|
* 將日志保存到文件中
|
*
|
* @param tag
|
* @param text
|
*/
|
private static void writeLogtoFile(String tag, String text) {// 新建或打开日志文件
|
SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA);
|
String needWriteMessage = tag + ": " + text;
|
try {
|
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "com.sinata.qkt.log", format.format(System.currentTimeMillis())+".txt");
|
File parentFile = file.getParentFile();
|
if (!parentFile.exists()) {
|
boolean mkdirs = parentFile.mkdirs();
|
}
|
if (!file.exists()) {
|
boolean newFile = file.createNewFile();
|
}
|
try {
|
FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖
|
BufferedWriter bufWriter = new BufferedWriter(filerWriter);
|
bufWriter.write(needWriteMessage);
|
bufWriter.newLine();
|
bufWriter.close();
|
filerWriter.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|