Reputation: 7574
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" );
Upvotes: 2
Views: 3458
Reputation: 2297
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.
Upvotes: 4
Reputation: 391
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
Upvotes: 5