2

I'm trying to write log statements to the sdcard. The way i have decided to do it is create a file on the sdcard through the Application Object. This way i can call a static method logToSdcard() from anywhere in the app.

The containing folder "/RR3log/" is created but every statement that i log is in its own file called "rr3LogFile.txt". So i have multiple rr3LogFile files containing one staement in each.

How can i write all statement to one rr3LogFile file? Thanks in advance Matt.

public class NfcScannerApplication extends Application{

    @Override
    public void onCreate() {
        super.onCreate();




        File storageDir = new File(Environment
                .getExternalStorageDirectory(), "/RR3log/");


        storageDir.mkdir();
        try {

            if(outfile == null){
            outfile=File.createTempFile("rr3LogFile", ".txt",storageDir);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }





public static void logToSdcard(String tag, String statement){


        Log.e(TAG, "inside logtosdcard$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");


                String state = android.os.Environment.getExternalStorageState();
                if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
                    try {
                        throw new IOException("SD Card is not mounted.  It is " + state + ".");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                DateTime now = new DateTime();
                DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y H:mm");
                String dateStr = fmt.print(now);


                try{


                    FileOutputStream fOut = new FileOutputStream(outfile);
                    OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
                    myOutWriter.append(dateStr + " " + tag + "     ");
                    myOutWriter.append(statement);
                    myOutWriter.append("\n");
                    myOutWriter.flush();
                    myOutWriter.close();
                    fOut.close();

                }catch(IOException e){
                    e.printStackTrace();
                }




    }


}

.

Then in an Activity anywhere in the app.

@Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "inside entryactivity onResume");
        NfcScannerApplication.logToSdcard(TAG, "inside entryactivity onResume" );
turtleboy
  • 8,210
  • 27
  • 100
  • 199
  • You can use `logcat` to write your logs. See this answer: http://stackoverflow.com/a/17609646/2198638. – Brtle Jul 16 '13 at 14:16
  • The way you do it you have one file per invocation of your app, so don't use createTempFile(). Then you have to append to the file, use [this FileOutputStream constructor](http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html#FileOutputStream%28java.io.File,%20boolean%29). – devconsole Jul 16 '13 at 14:19
  • @AddrallynWigolath Hi it creates the log file but when i navigate to it through the File Manager and click on it, it says 'application not available'. Any ideas why? thanks – turtleboy Jul 16 '13 at 14:53
  • You can try to change the extension (.txt instead of .log) or send it by email. – Brtle Jul 16 '13 at 15:02
  • @AddrallynWigolath thanks that works a treat. If i want the date and time on the log statement do i have to write it there myself or is there a logcat option? Also if my app is running for a week or so is there any impact writing so many log statements to a file, is there a file size limit? – turtleboy Jul 16 '13 at 15:16
  • For the date and time, you can use the `-v time` option (more information here: http://developer.android.com/tools/help/logcat.html). Writing the file is quite expensive, it will impact your application. Personnally, I just use this method to debug my application. You can see the buffer size with the `-g` option. – Brtle Jul 16 '13 at 15:48
  • hi i've tried using this but still no time being logged. String command = "logcat -d *:V -v time"; – turtleboy Jul 16 '13 at 16:03
  • sorry did the following and works fine. String command = "logcat -v time -d *:V -v time"; – turtleboy Jul 16 '13 at 16:05
  • @AddrallynWigolath it seems to be working fine now, but one last problem is that when i use the app then come out of the app, it seems to wipe the file and create a new one so the data from 5 mins ago is lost. Is there a way around this? – turtleboy Jul 16 '13 at 16:12
  • This method create a new file each time. According to http://stackoverflow.com/a/11548250/2198638, the `-f` option can be a solution for you but I didn't try it. – Brtle Jul 17 '13 at 07:29
  • @AddrallynWigolath ok thanks. i tried the following. String filename = context.getExternalFilesDir(null).getPath() + File.separator + "RR3.txt"; String command = "logcat -f "+ filename + " -v time -d *:V -v time"; – turtleboy Jul 17 '13 at 09:07
  • But it still creates a new file. do you think there could be an alternative to file.createNewFile(); ? – turtleboy Jul 17 '13 at 09:08
  • If you use the `-f` option, you don't have to use `file.createNewFile();`. I put the code in an answer, it will be easier. – Brtle Jul 17 '13 at 09:23

2 Answers2

5

In your logToSdcard Method create the FileOutputStream with an additional parameter:

FileOutputStream fOut = new FileOutputStream(outfile, true);

The true paramters says that contents will be appended to the file. See also FileOutputStream

Michael Schmidt
  • 391
  • 2
  • 14
  • it's still creating multiple log files but now in some of them there are multiple log statements. why is it creating multiple files? – turtleboy Jul 16 '13 at 15:03
4

Try that:

public static void printLog(Context context){
    String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
    String command = "logcat -f "+ filename + " -v time -d *:V";

    Log.d(TAG, "command: " + command);

    try{
        Runtime.getRuntime().exec(command);
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

The logs will be saved continuously until the application is exited.

Brtle
  • 2,297
  • 1
  • 19
  • 26
  • Hey Thanks alot works fine. I.ve noticed though if you go into the app, do something then view the file sometimes it is not written straigh away but if you view the file later it seems to have then written it. Apart from that brilliant. thanks alot for your help. matt – turtleboy Jul 17 '13 at 09:34
  • Actually just one last question. I have the following in my lauching activity. NfcScannerApplication.logToSdcard(this ); Do i have to call this method you have given me in every activity i what logged or because the method is in the appliction object will the entire app get logged? – turtleboy Jul 17 '13 at 09:39
  • The entire app get logged but you can filter tags. For instance: `logcat -f "+ filename + " -v time -d -s Tag1 Tag2`. – Brtle Jul 17 '13 at 09:48
  • no that's fine i want the entire app logged for debugging purposes. Thanks. – turtleboy Jul 17 '13 at 10:03
  • Hi when does the logging get flushed to the file, When you exit the app or navigate back to the activity where the logging method is first called? it just seems a little inconsistent when the data gets written. sometimes i have to open the app again for the data to get flushed to the file – turtleboy Jul 17 '13 at 10:44
  • Try to remove the `-d`: `"logcat -f "+ filename + " -v time *:V"` – Brtle Jul 17 '13 at 11:54
  • great stuff! i'll leave you alone now;) – turtleboy Jul 17 '13 at 12:20