I have created a method which shows log in logcat and also writes into the file. Every time this method is called it appends String in file. There are so many read/write operations on disk/non-volatile storage/SD card happening. I want to batch these operations so that minimum SD card read/write happens and i do not miss any log info.
I have a idea to store logs in static StringBuilder variable and check if its length>200000 then write to file otherwise append it in variable. Will that work perfectly, how other developer handle this task?
public static void log(String tag, String s, @ErrorType int error) {
Log.d(tag, s);
if (MyApplication.sExternalStorageDirectory == null) {
new NullPointerException("sExternalStorageDirectory is null")
.printStackTrace();
return;
}
String fileName = "logs";
String fileExtension = ".txt";
if (error == ErrorType.WEBSERVICE_RESPONSE_ERROR) {
fileName = "web_api_error_log";
} else if (error == ErrorType.CLIENT_SIDE_ERROR) {
fileName = "client_log";
}
File f = new File(MyApplication.sExternalStorageDirectory, fileName + fileExtension);
try {
if (!f.exists()) {
f.createNewFile();
}
BufferedWriter bfw = new BufferedWriter(new FileWriter(f, true));
bfw.append(tag + "->" + s);
bfw.newLine();
bfw.close();
} catch (IOException e) {
e.printStackTrace();
}
}