LogCat存储在circular memory buffers中。
1、可以通过命令来导出Log:
引用
adb logcat -d > logcat.txt
2、在程序中获取Log的方法:
添加日志读取权限:
<uses-permission android:name="android.permission.READ_LOGS" />代码如下:
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保存到文件上查看