【小知识点总结】保存android日志logcat到文件中
16lz
2021-01-25
LogCat存储在circular memory buffers中。
1、可以通过命令来导出Log:
2、在程序中获取Log的方法:
添加日志读取权限:
代码如下:
public class LogTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
//可以写到TextView中
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(log.toString());
//也可以写到app指定的文件中去
String logPath = Environment.getExternalStorageDirectory().getPath() + "/logcat.log";
LogUtils.f(logPath, log.toString(), false);
} catch (IOException e) {
}
}
}
LogUtils代码:
public final class LogUtils {
public static void f(String logPath, String logData, boolean override) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(logPath, !override));
if (!override) {
writer.append(logData);
} else {
writer.write(logData);
}
writer.newLine();
} catch (FileNotFoundException e) {
e(new LogUtils(), e.toString());
} catch (IOException e) {
e(new LogUtils(), e.toString());
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
} catch (Exception e2) {
e(new LogUtils(), e2.toString());
}
}
}
}
释放资源代码:
if (bufferedReader != null)
{
try
{
bufferedReader.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
if (process != null)
{
process.destroy();
}
其他相关链接:Android的log保存到文件上查看
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- GitHub 标星 2.5K+!教你通过玩游戏的方式学习 VIM!
- 如何在后台运行Linux命令?
- 一款常用的 Squid 日志分析工具
- No.11 使用firewall配置的防火墙策略的生效模式
- GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
- RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
- Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
- Android开发工具之Android(安卓)Studio----Gradle