将android logcat数据写入文件

64jmpszr  于 2022-12-09  发布在  Android
关注(0)|答案(4)|浏览(195)

我想在用户需要收集日志时将Android logcat转储到一个文件中。通过adb工具,我们可以使用adb logcat -f filename将日志重定向到一个文件中,但我如何通过编程实现这一点呢?

zpjtge22

zpjtge221#

下面是阅读日志的example
您可以将其更改为写入文件,而不是写入TextView
需要AndroidManifest中的权限:

<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 tv = (TextView) findViewById(R.id.textView1);
      tv.setText(log.toString());
    } catch (IOException e) {
    }
  }
}
a0zr77ik

a0zr77ik2#

Logcat可以直接写入文件:

public static void saveLogcatToFile(Context context) {    
    String fileName = "logcat_"+System.currentTimeMillis()+".txt";
    File outputFile = new File(context.getExternalCacheDir(),fileName);
    @SuppressWarnings("unused")
    Process process = Runtime.getRuntime().exec("logcat -f "+outputFile.getAbsolutePath());
}

有关logcat更多信息:请参阅http://developer.android.com/tools/debugging/debugging-log.html

9cbw7uwe

9cbw7uwe3#

或者你可以试试这个变种

try {
    final File path = new File(
            Environment.getExternalStorageDirectory(), "DBO_logs5");
    if (!path.exists()) {
        path.mkdir();
    }
    Runtime.getRuntime().exec(
            "logcat  -d -f " + path + File.separator
                    + "dbo_logcat"
                    + ".txt");
} catch (IOException e) {
    e.printStackTrace();
}
qltillow

qltillow4#

public static void writeLogToFile(Context context) {    
    String fileName = "logcat.txt";
    File file= new File(context.getExternalCacheDir(),fileName);
    if(!file.exists())
         file.createNewFile();
    String command = "logcat -f "+file.getAbsolutePath();
    Runtime.getRuntime().exec(command);
}

上述方法会将所有日志写入文件。另外,请在清单文件中添加以下权限

<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

相关问题