Logging to a file on Android

You could use Thread.setUncaughtExceptionHandler() to catch the Exceptions.

Writing to SD Card is as simple as retrieving the directory for the card using Environment.getExternalStorageDirectory() and creating a file there.

File f = new File(Environment.getExternalStorageDirectory(),filename);

You will need to give you app the correct permission to write to the SD Card by adding this to your Manifest:

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

Log4j or slf4j can also be used as logging frameworks in Android together with logcat. See the project android-logging-log4j. Configuring logging to a (rotating) file(s) is very easy.

 static {
    final LogConfigurator logConfigurator = new LogConfigurator();

    logConfigurator.setFileName(Environment.getExternalStorageDirectory() + "myapp.log");
    logConfigurator.setRootLevel(Level.DEBUG);
    // Set log level of a specific logger
    logConfigurator.setLevel("org.apache", Level.ERROR);
    logConfigurator.configure();
}

You could take a look at microlog4android. They have a solution ready to log to a file.

https://github.com/johanlkarlsson/microlog4android


I tried both options above (microlog4android & android-logging-log4j) and they were a struggle to try to get working. Once they compiled fine then I would get Runtime java.lang.NoClassDefFoundError.

So then I stumbled on logback-android ... also found here http://logback.qos.ch/

It has much better instructions and I got it working in a couple hours.

This appears to be the best logging solution for Android.