As a long time log4j user, it is really enjoying to find log4j is available on Android with the help of this project https://code.google.com/p/android-logging-log4j/
For my current Android projects, I am writing logs both to logcat and a file on SD-Card, and the logging file is of great value to my project.
But some recent feedbacks from my beta testing users revealed that if the the SD-Card is removed while my application is writing logs, it will cause a Force-Close.
My current solution is to detect if external storage is mounted when log4j is first used; if no external storage is detected, I will disable log file output.
import java.io.File;
import org.apache.log4j.Level;
import android.os.Environment;
import de.mindpipe.android.logging.log4j.LogConfigurator;
public class ConfigureLog4j {
private static boolean configured = false;
public static void configure() {
if (configured == true) {
return;
}
String status = Environment.getExternalStorageState();
final LogConfigurator logConfigurator = new LogConfigurator();
if (status.equals(Environment.MEDIA_MOUNTED)) {
logConfigurator.setUseFileAppender(true);
logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "msgant.log");
} else {
logConfigurator.setUseFileAppender(false);
}
logConfigurator.setRootLevel(Level.DEBUG);
// Set log level of a specific logger
logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.configure();
configured = true;
}
}
It is far from a perfect solution, and actually, it will not solve my current issue with log4j crash, because I can not decide when users try to unmount SD-Card.
Or I should make a wrapper around log4j, and implement the storage detection logic there?
you can always listen to the sdcard events and reconfigure log4j accordingly.
this will allow you to reconfigure log4j when the card is removed (you can probably use the device internal storage till such a time a SD card is inserted again.
The
SdCardEventListenershould extendBroadcastReceiverand then reconfigure the logger as necessary.