How to safely use android-logging-log4j when writing logs to external storage (SD-Card)?

As a long time log4j user, he really likes to find log4j available on Android with this project https://code.google.com/p/android-logging-log4j/

For my current Android projects, I write logs for both the logcat and the file on the SD-Card and the log file is of great importance to my project.

But some recent feedback from my beta users showed that if the SD-Card is removed while my app is writing logs, it will force shutdown.

My current solution is to determine if external storage is mounted on first use of log4j; if no external storage is found i turn off 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;
    }
}

      

This is far from a perfect solution and it doesn't actually solve my current log4j log file problem because I can't seem to resolve when users try to disable SD-Card.

Or should I make a wrapper around log4j and implement the storage detection logic there?

+3


source to share


2 answers


you can always listen for sdcard events and reconfigure log4j accordingly.

<receiver android:name="com.project.events.SdCardEventListener" >
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_REMOVED" />
        <action android:name="android.intent.action.MEDIA_MOUNTED" />
    </intent-filter>
</receiver>

      



this will allow you to reconfigure log4j when the card is removed (perhaps you can use the internal storage of the device until the SD card is inserted.

SdCardEventListener

must expand BroadcastReceiver

and then reconfigure the registrar if necessary.

+2


source


I could log4j send logs to SocketAppender while listening to your server. The only problem is that If the remote server is down, the logging requests are simply dropped

.



0


source