title: How to safely use android-logging-log4j when writing logs on external storage(SD-Card)?
body: <p>As a long time log4j user, it is really enjoying to find log4j is available on Android with the help of this project <a href="https://code.google.com/p/android-logging-log4j/" rel="nofollow">https://code.google.com/p/android-logging-log4j/</a></p>
  
  <p>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. </p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>Or I should make a wrapper around log4j, and implement the storage detection logic there?</p>