Write android logcat data to a file

2019-01-04 06:19发布

I want to dump Android logcat in a file whenever user wants to collect logs. Through adb tools we can redirect logs to a file using adb logcat -f filename, but how can I do this programmatically?

4条回答
Melony?
2楼-- · 2019-01-04 07:00

Logcat can write directly to a file:

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

more info on logcat: see http://developer.android.com/tools/debugging/debugging-log.html

查看更多
老娘就宠你
3楼-- · 2019-01-04 07:02

Or you can try this 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();
}
查看更多
该账号已被封号
4楼-- · 2019-01-04 07:11

Here is an example of reading the logs.

You could change this to write to a file instead of to a TextView.

Need permission in AndroidManifest:

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

Code:

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) {
    }
  }
}
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-04 07:11
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);
}

Above method will write all logs into the file. Also please add below permissions in Manifest file

<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
查看更多
登录 后发表回答