将android logcat数据写入文件

时间:2011-05-30 10:16:38

标签: android logging

我想在用户想要收集日志时将Android logcat转储到文件中。通过adb工具,我们可以使用adb logcat -f filename将日志重定向到文件,但是如何以编程方式执行此操作?

4 个答案:

答案 0 :(得分:123)

这是阅读日志的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) {
    }
  }
}

答案 1 :(得分:39)

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

答案 2 :(得分:1)

或者你可以试试这个varian

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();
}

答案 3 :(得分:0)

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" />