91 lines
3.5 KiB
Java
91 lines
3.5 KiB
Java
package com.shayu.phonelive.utils;
|
|
|
|
import static java.text.DateFormat.DEFAULT;
|
|
|
|
import android.content.Context;
|
|
|
|
import com.yunbao.common.CommonAppConfig;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.File;
|
|
import java.io.FileOutputStream;
|
|
import java.io.InputStreamReader;
|
|
import java.io.PrintWriter;
|
|
import java.text.ParseException;
|
|
import java.text.SimpleDateFormat;
|
|
import java.util.Calendar;
|
|
import java.util.Date;
|
|
import java.util.Locale;
|
|
import java.util.Objects;
|
|
|
|
public class LogUtils {
|
|
/**
|
|
* 采集所有日志
|
|
*/
|
|
public static void start(Context context) {
|
|
new Thread(new Runnable() {
|
|
@Override
|
|
public void run() {
|
|
try {
|
|
|
|
String[] exec = new String[]{"logcat", "-c"};
|
|
Runtime.getRuntime().exec(exec).waitFor();
|
|
|
|
exec = new String[]{"logcat", "-v", "color", "UTC-8"};
|
|
|
|
Process process = Runtime.getRuntime().exec(exec);
|
|
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
|
String line;
|
|
PrintWriter writer = null;
|
|
String title = "[PDLIVE]" + CommonAppConfig.getInstance().getUid() + "_";
|
|
String today = title + SimpleDateFormat.getDateInstance(DEFAULT, Locale.CHINA).format(new Date());
|
|
File dir = new File(context.getDir("files", Context.MODE_PRIVATE).getAbsolutePath() + File.separator);
|
|
if (dir.listFiles() != null) {
|
|
for (File file : dir.listFiles()) {
|
|
if (file.getName().endsWith(".log") && !"error.log".equals(file.getName())) {
|
|
String fileName = file.getName().replace(".log", "").split("_")[1];
|
|
if (isDelLog(fileName)) {
|
|
file.delete();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
File saveFile = new File(context.getDir("files", Context.MODE_PRIVATE).getAbsolutePath() + File.separator + today + ".log");
|
|
FileOutputStream os = new FileOutputStream(saveFile, true);
|
|
writer = new PrintWriter(os);
|
|
while ((line = bufferedReader.readLine()) != null) {
|
|
writer.append(line).write("\n");
|
|
writer.flush();
|
|
}
|
|
writer.flush();
|
|
writer.close();
|
|
exec = new String[]{"logcat", "-c"};
|
|
Runtime.getRuntime().exec(exec).waitFor();
|
|
bufferedReader.close();
|
|
start(context);
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}).start();
|
|
|
|
}
|
|
|
|
/**
|
|
* 判断是否是要删除的日志
|
|
**/
|
|
private static boolean isDelLog(String time) {
|
|
try {
|
|
Calendar timeCal = Calendar.getInstance(Locale.CHINA);
|
|
timeCal.setTime(Objects.requireNonNull(SimpleDateFormat.getDateInstance(DEFAULT, Locale.CHINA).parse(time)));
|
|
Calendar calendar = Calendar.getInstance(Locale.CHINA);
|
|
calendar.setTime(new Date());
|
|
calendar.add(Calendar.DATE, -3);
|
|
return calendar.after(timeCal);
|
|
} catch (ParseException e) {
|
|
e.printStackTrace();
|
|
}
|
|
return false;
|
|
}
|
|
}
|