0%

Android的本地Log缓存抓取

LogcatUtil

  • 抓取本地日志的工具类
/**
* 用于抓取Android日志的工具类
*/
public class LogcatUtil {
// 日志的类型
public enum LogType {
Verbose,
Debug,
Info,
Warn,
Error,
Fatal,
Silent,
}

public static StringBuffer SBF = new StringBuffer();

/**
* 获取error的log
* @param tag
* @param lines
* @return
*/
public static String GetErrorLog(String tag, int lines) {
return GetLog(tag, LogType.Error, lines);
}
/**
* 获取当前
* @param lines 最大行数
* @return
*/
public static String GetLog(String tag, LogType type, int lines) {
// 校验tag
if (tag == null || tag.length() == 0 ) {
tag = "*";
}
// 校验type
String typeStr = "*";
switch (type) {
case Verbose: {
typeStr = "v";
break;
}
case Debug: {
typeStr = "d";
break;
}
case Info: {
typeStr = "i";
break;
}
case Warn: {
typeStr = "w";
break;
}
case Error: {
typeStr = "e";
break;
}
case Fatal: {
typeStr = "f";
break;
}
case Silent: {
typeStr = "*";
break;
}
}
// 校验lines
if (lines < 0) {
lines = 100;
}
// 最多抓999条
if (lines > 999) {
lines = 999;
}
// 清空缓存
SBF.setLength(0);
ArrayList<String> cmdLine=new ArrayList<String>(); //设置命令 logcat -d 读取日志
cmdLine.add("logcat");
cmdLine.add("-d");
if (!tag.equals("*") || !typeStr.equals("*")) {
cmdLine.add(tag + ":" + typeStr);
}
try {
Process process = Runtime.getRuntime().exec(cmdLine.toArray(new String[cmdLine.size()])); //捕获日志
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); //将捕获内容转换为BufferedReader
String str = null;
while(lines > 0 && (str=bufferedReader.readLine()) != null) //开始读取日志,每次读取一行
{
SBF.append("\n" + str);
lines--;
}
bufferedReader.close();
process.getInputStream().close();
}catch (Exception e) {
e.printStackTrace();
}
// System.out.println(SBF.toString());
return SBF.toString();
}
}

欢迎关注我的其它发布渠道