Android Writing Logs to text File


Question

I'm Trying to Write Logs to Custom Log.txt File on Android File using this code of Mine but then this method creates file but contains nothing. Basically I want to read previous contents of the file and then append my data with the existing content.

The Code is as follows :

public static void write(String str) 
    {
        InputStream fileInputStream = null;
        FileOutputStream fileOutpurStream = null;
        try
        { 
            fileInputStream = new FileInputStream(file);
            fileOutpurStream = new FileOutputStream(file);
            if(file.exists())
            {
                int ch = 0;
                int current = 0;
                StringBuffer buffer = new StringBuffer();
                while((ch = fileInputStream.read()) != -1)
                {
                    buffer.append((char) ch);
                    current++;
                }
                byte data[]=new byte[(int)file.length()];
                fileInputStream.read(data);   
                fileOutpurStream.write(data);
                fileOutpurStream.write(str.getBytes(),0,str.getBytes().length);
                fileOutpurStream.flush();
            } 
            else
            {   
                file.createNewFile();
                fileOutpurStream.write(str.getBytes(),0,str.getBytes().length);
                fileOutpurStream.flush();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                fileInputStream.close();
                fileOutpurStream.flush();
                fileOutpurStream.close();
                fileOutpurStream = null;
                fileInputStream = null;
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
1
119
4/27/2013 1:29:16 PM

Accepted Answer

Hope this can help...

public void appendLog(String text)
{       
   File logFile = new File("sdcard/log.file");
   if (!logFile.exists())
   {
      try
      {
         logFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}
237
6/2/2011 2:15:55 AM

For those new to Java logging in general and Android logging

  1. Log4j is generic java logging implementation and is now a project of Apache software foundation. It is not Android specific and so has some incompatibilities with Android.
  2. SL4J is not a logging implementation, It is an abstraction layer. It helps avoid a situations like, each 3rd party library dependencies to a project, trying to using its own logging implementation like Log4j. Source.

Some options for logging to txt in Android are below

  1. Use logcat -f as in this answer to log to file. Note that from Android 4.2, READ_LOGS permission doesn't have any impact and every Application (unless phone is rooted) could only read its own logs. The disadvantage here is logcat buffer is circular and has a size limit. You might not get earlier logs.
  2. Use microlog4android ( written for mobile devices like Android ) as in earlier answer. There could be a way, but I couldn't figure, how to use microlog4Android for logging to application internal storage. Only option for logs path was external storage like sdcard and so I couldn't use it.
  3. Use Log4j with android-logging-log4j. What does android-logging-log4j do ? It makes Log4j easier to use in Android by giving two functions.

    • option to send logs to logcat in addition to logging file
    • a simple way to set Log4j configuration options like file path, max file size, number of backups etc by providing LogConfigurator class.

    Simple example below. Notice that logger object in below example is a Log4j object returned and not an android-logging-log4j class. So android-logging-log4j is used only for configuring Log4j.

  4. Yet to try LogBack. LogBack is developed by same person who came up with Log4J 1.x and SL4J libraries. Not related to Log4j 2.x though.

Steps for using Log4j in Android.

  1. Add both log4j-1.2.x.jar and android-logging-log4j-1.0.3.jar to the libs folder.

  2. Add permissions only if using external storage
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  3. Write Log4j helper class

    package com.example.logger;
    
    import android.os.Environment;
    import de.mindpipe.android.logging.log4j.LogConfigurator;
    
    public class Log4jHelper {
        private final static LogConfigurator mLogConfigrator = new LogConfigurator();
    
        static {
            configureLog4j();
        }
    
        private static void configureLog4j() {
            String fileName = Environment.getExternalStorageDirectory() + "/" + "log4j.log";
            String filePattern = "%d - [%c] - %p : %m%n";
            int maxBackupSize = 10;
            long maxFileSize = 1024 * 1024;
    
            configure( fileName, filePattern, maxBackupSize, maxFileSize );
        }
    
        private static void configure( String fileName, String filePattern, int maxBackupSize, long maxFileSize ) {
            mLogConfigrator.setFileName( fileName );
            mLogConfigrator.setMaxFileSize( maxFileSize );
            mLogConfigrator.setFilePattern(filePattern);
            mLogConfigrator.setMaxBackupSize(maxBackupSize);
            mLogConfigrator.setUseLogCatAppender(true);
            mLogConfigrator.configure();
    
        }
    
        public static org.apache.log4j.Logger getLogger( String name ) {
            org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger( name );
            return logger;
        }
    }
    
  4. In Activity class

    org.apache.log4j.Logger log= Log4jHelper.getLogger( "YourActivity" );
    log.error("Error");
    log.info("Info");
    log.warn("Warn");
    

Example Source. Note that, log4j 2.x ( improved functionalities ) rewritten from scratch is not backward comptible with log4j 1.x. So you have to use log4j 1.2.x jar with android-logging-log4j jar. I was able to log to application internal file and later email the file with setReadable(true, false)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon