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 06:55

Use slf4android lib.
It's simple implementation of slf4j api using android java.util.logging.*.

Features:

  • logging to file out of the box
  • logging to any other destination by LoggerConfiguration.configuration().addHandlerToLogger
  • shake your device to send logs with screenshot via email
  • really small, it tooks only ~55kB

slf4android is maintained mainly by @miensol.

Read more about slf4android on our blog:

查看更多
何处买醉
3楼-- · 2019-01-01 06:57

You can use the library I've written. It's very easy to use:

Add this dependency to your gradle file:

dependencies {
    compile 'com.github.danylovolokh:android-logger:1.0.2'
}

Initialize the library in the Application class:

File logsDirectory = AndroidLogger.getDefaultLogFilesDirectory(this);
    int logFileMaxSizeBytes = 2 * 1024 * 1024; // 2Mb
    try {
        AndroidLogger.initialize(
                this,
                logsDirectory,
                "Log_File_Name",
                logFileMaxSizeBytes,
                false
                );
    } catch (IOException e) {
        // Some error happened - most likely there is no free space on the system
    }

This is how you use the library:

AndroidLogger.v("TAG", "Verbose Message");

And this is how to retrieve the logs:

AndroidLogger.processPendingLogsStopAndGetLogFiles(new AndroidLogger.GetFilesCallback() {
        @Override
        public void onFiles(File[] logFiles) {
            // get everything you need from these files
            try {
                AndroidLogger.reinitAndroidLogger();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

Here is the link to the github page with more information: https://github.com/danylovolokh/AndroidLogger

Hope it helps.

查看更多
爱死公子算了
4楼-- · 2019-01-01 07:00

This may be late but hope this may help.. Try this....

public void writefile()
    {
        File externalStorageDir = Environment.getExternalStorageDirectory();
        File myFile = new File(externalStorageDir , "yourfilename.txt");

        if(myFile.exists())
        {
           try
           {

        FileOutputStream fostream = new FileOutputStream(myFile);
        OutputStreamWriter oswriter = new OutputStreamWriter(fostream); 
        BufferedWriter bwriter = new BufferedWriter(oswriter);   
        bwriter.write("Hi welcome ");
        bwriter.newLine();            
        bwriter.close(); 
        oswriter.close(); 
        fostream.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
        else
        {
            try {
                myFile.createNewFile();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }

here bfwritter.newline writes your text into the file. And add the permission

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

in your manifest file without fail.

查看更多
有味是清欢
5楼-- · 2019-01-01 07:00

This variant is much shorter

try {
    final File path = new File(
            Environment.getExternalStorageDirectory(), "DBO_logs5");
    if (!path.exists()) {
        path.mkdir();
    }
    Runtime.getRuntime().exec(
            "logcat  -d -f " + path + File.separator
                    + "dbo_logcat"
                    + ".txt");
} catch (IOException e) {
    e.printStackTrace();
}
查看更多
唯独是你
6楼-- · 2019-01-01 07:03

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)

查看更多
时光乱了年华
7楼-- · 2019-01-01 07:03

Warning: I may be totally misunderstanding you, but if all you want is a log file, why sweat?

Put this in a bat file (change the path to your tools directory, and yourappname is of course your app's name):

cd "C:\devAndroid\Software\android-sdk-windows-1.6_r1\android-sdk-windows-1.6_r1\tools"
adb logcat -v time   ActivityManager:W  yourappname:D  *:W >"C:\devAndroid\log\yourappname.log"

Then in your code just do something similar to this:

Log.d("yourappname", "Your message");

To create the log, connect the USB cable and run your bat file.

Regards

查看更多
登录 后发表回答