Android Writing Logs to text File

2019-01-01 06:34发布

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();
            }
        }

标签: android
12条回答
大哥的爱人
2楼-- · 2019-01-01 07:06

I solved this problem with following piece of code in command line way:

File outputFile = new File("pathToFile"); 
Runtime.getRuntime().exec("logcat -c");
Runtime.getRuntime().exec("logcat -v time -f " + outputFile.getAbsolutePath())

Where "time" option adds metadata field details for date, invocation time, priority/tag, and PID of the process issuing the message.

Then in your code just do something similar to this (using android.util.Log):

Log.d("yourappname", "Your message");
查看更多
忆尘夕之涩
3楼-- · 2019-01-01 07:09

microlog4android works for me but the documentation is pretty poor. All they need to add is a this is a quick start tutorial.

Here is a quick tutorial I found.

  1. Add the following static variable in your main Activity:

    private static final Logger logger = LoggerFactory.getLogger();
    
  2. Add the following to your onCreate() method:

    PropertyConfigurator.getConfigurator(this).configure();
    
  3. Create a file named microlog.properties and store it in assets directory

  4. Edit the microlog.properties file as follows:

    microlog.level=DEBUG
    microlog.appender=LogCatAppender;FileAppender
    microlog.formatter=PatternFormatter
    microlog.formatter.PatternFormatter.pattern=%c [%P] %m %T
    
  5. Add logging statements like this:

    logger.debug("M4A");
    

For each class you create a logger object as specified in 1)

6.You may be add the following permission:

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

Here is the source for tutorial

查看更多
永恒的永恒
4楼-- · 2019-01-01 07:09

I have created a simple, lightweight class (about 260 LoC) that extends the standard android.util.Log implementation with file based logging:
Every log message is logged via android.util.Log and also written to a text file on the device.

You can find it on github:
https://github.com/volkerv/FileLog

查看更多
荒废的爱情
5楼-- · 2019-01-01 07:11

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

http://code.google.com/p/microlog4android/

查看更多
路过你的时光
6楼-- · 2019-01-01 07:14

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();
   }
}
查看更多
姐姐魅力值爆表
7楼-- · 2019-01-01 07:15

In general, you must have a file handle before opening the stream. You have a fileOutputStream handle before createNewFile() in the else block. The stream does not create the file if it doesn't exist.

Not really android specific, but that's a lot IO for this purpose. What if you do many "write" operations one after another? You will be reading the entire contents and writing the entire contents, taking time, and more importantly, battery life.

I suggest using java.io.RandomAccessFile, seek()'ing to the end, then writeChars() to append. It will be much cleaner code and likely much faster.

查看更多
登录 后发表回答