Skip to content

Instantly share code, notes, and snippets.

@mo7amd89
Created October 30, 2022 08:52
Show Gist options
  • Save mo7amd89/0771cddcf9e058fcc00db02dba35a06f to your computer and use it in GitHub Desktop.
Save mo7amd89/0771cddcf9e058fcc00db02dba35a06f to your computer and use it in GitHub Desktop.
store Logs in a txt file using the android.util.log
import android.os.Environment;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.FileHandler;
/**
* @author Rakesh.Jha
* Date - 07/10/2013
* Definition - Logger file use to keep Log info to external SD with the simple method
*/
public class FileLogger {
public static FileHandler logger = null;
private static String filename = "ProjectName_Log";
static boolean isExternalStorageAvailable = false;
static boolean isExternalStorageWriteable = false;
static String state = Environment.getExternalStorageState();
public static void addRecordToLog(String message) {
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
isExternalStorageAvailable = isExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
isExternalStorageAvailable = true;
isExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
isExternalStorageAvailable = isExternalStorageWriteable = false;
}
File dir = new File("/sdcard/Files/ITS_A90/logs");
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (!dir.exists()) {
Log.d("Dir created ", "Dir created ");
dir.mkdirs();
}
File logFile = new File("/sdcard/Files/ITS_A90/logs/" + filename + ".txt");
if (!logFile.exists()) {
try {
Log.d("File created ", "File created ");
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));
String msg = getDate() + " " + message;
buf.write(msg + "\r\n");
//buf.append(message);
buf.newLine();
buf.flush();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static String getDate() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss"); //EEEE, dd-MMM-yyyy hh-mm-ss a
Calendar calendar = Calendar.getInstance();
return simpleDateFormat.format(calendar.getTime());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment