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?
adb logcat –d > filename.txt This command will extract the logcat information from the connected device and redirects the output to a file on the PC. The option –d will take care that the output will stop when all output is flushed.
They are stored as circular memory buffers on the device. If you run "adb logcat > myfile" on your host system, you can retrieve the content into a file.
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) { } } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With