This question already has answers here:
How do I write the exception from printStackTrace() into a text file in Java?
(5 answers)
Closed 8 years ago.
My program is crashing in device. I want to exactly catch the log of my program while running in my device .i.e I want to write the log to my sd card, up to the point of crashing. How can I achieve this?
Try this
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this)); // add this to your activity page
public class ExceptionHandler implements
java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final String LINE_SEPARATOR = "\n";
UncaughtExceptionHandler defaultUEH;
public ExceptionHandler(Context con) {
myContext = con;
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
#SuppressWarnings("deprecation")
public void uncaughtException(Thread thread, Throwable exception) {
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
StringBuilder errorReport = new StringBuilder();
errorReport.append("************ CAUSE OF ERROR ************\n\n");
errorReport.append(stackTrace.toString());
errorReport.append("\n************ DEVICE INFORMATION ***********\n");
errorReport.append("Brand: ");
errorReport.append(Build.BRAND);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Device: ");
errorReport.append(Build.DEVICE);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Model: ");
errorReport.append(Build.MODEL);
errorReport.append(LINE_SEPARATOR);
File root = android.os.Environment.getExternalStorageDirectory();
String currentDateTimeString = DateFormat.getDateTimeInstance().format(
new Date());
File dir = new File(root.getAbsolutePath() + "/dir_name/log");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "log.txt");
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(currentDateTimeString + ":" + errorReport.toString());
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
defaultUEH.uncaughtException(thread, exception);
System.exit(0);
}
}
Once I got this from somewhere in SO. Try this:
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time *:V";
Log.d(TAG, "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
This prints log continuously until the app exit.
Try this :
public void appendLog(String text) {
File logFile = new File("sdcard/log.file");
if (!logFile.exists()) {
try {
logFile.createNewFile();
}
catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
If you want to catch only the exception with the stacktrace, which in most cases is enough to get what was wrong, then ACRA is a winning solution.
If you do want to write something to your SD card then take in consideration that you can't assume that any device has external storage that you can write to. Unless you validate this.
To bring another option of writing to external storage you can use this simple library:
android-simple-storage
This is how you use it:
Prepare somewhere in your app:
Storage storage = SimpleStorage.getExternalStorage();
// create your own directory
storage.createDirectory("MyDir");
// create the file you want to write to inside your new directory
storage.createFile("MyDir", "MyFile.txt", "");
Append any string (or byte[]) whenever you want to this file:
storage.appendFile("MyDir", "MyFile.txt", "your log line");
You can create/read/update/delete with this tiny library files on internal and external storages very easy. And, take into consideration that writing to the same file will increase the space it takes. You can use getSize() from the same library to validate.
Related
I am a beginner when it comes to Android. I encountered a problem, regarding writing to a file. I want to save to a file the input I get in a form. However, the piece of code that I wrote is not writing in my file. Could anyone please help me?
The code looks like that:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
File file = new File("D:\\config.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
out.write(s.toString());
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
So, I have a form containing 3 fields: the name of an event, the date and the description. These I want to save to my file. I should mention that I use an emulator for testing.
Use following path for file. It will write file to your root folder of storage.
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
writeToFile("File content".getBytes(), file);
writeToFile
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
Don't forget to add following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
https://github.com/rznazn/GPS-Data-Logger/blob/master/app/src/main/java/com/example/android/gpsdatalogger/StorageManager.java
Here is a... nearly complete class for writing to the documents folder on the emulated external storage of the device.
Don't forget to add the write permissions to manifest.
so im trying to write data that I recieve from a socket into text file and then read those data.
I have these 2 methods in my MainActivity (just tests to see how read and write from/into a file works) :
public void WriteBtn() {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("Test");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ReadBtn() {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[256];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
I call them with buttons but I was wondering, where does it save my "mytextfile.txt" ???
Take a look at Context.getExternalFilesDir() and pass it Environment.DIRECTORY_DOCUMENTS. That should give you the default output path for text files.
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
EDIT
I just tested this. It looks like Context.openFileOutput() dumps everything, regardless of file type, to Conext.getFilesDir()
https://developer.android.com/reference/android/content/Context.html#getFilesDir()
I am trying to create a .txt file in android, I have tested a lot of options how to achieve this, I think the file is created but I can't find it, it should be writed somehow public in a public directory that I can access it.
Example:
cacheFile = new java.io.File(getFilesDir(), "cache.txt");
if(cacheFile.exists() && !cacheFile.isDirectory()) {
try {
writer = new FileWriter(cacheFile);
BufferedReader br = new BufferedReader(new FileReader(cacheFile));
String tempo;
while((tempo = br.readLine()) != null){
Log.i("TEST","Reading from cache "+tempo);
if (tempo.contains("http")) {
musicUrl.add(tempo);
}
else {
myDataList.add(tempo);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
else {
try {
Log.i("TEST", "Creating the cache ? " + cacheFile.createNewFile() + " in " + getFilesDir());
writer = new FileWriter(cacheFile);
} catch (IOException e) {
e.printStackTrace();
}
}
What other option I've tried: Android File on Internal Storage not found
you should use one of the following:
getExternalFilesDir()
getExternalStoargeDir()
the first will create a file in /sdcard/android/app.package/file
the second will be the root of /sdcard/
The call that you currently make, getFilesDir(), is returning the path in /data/data/app.package/file which is not accessable to anything other then your application.
I tried to find this but couldn't find and results. Apologies if this is a duplicate.
I would like to have android logs written to a file. But i do not wish them to be written to the file in the end, rather as the log statement is executed, it should be written into this file.
But i do not wish them to be written to the file in the end, rather as the log statement is executed, it should be written into this file.
Then write one or more methods that log to a file, possibly in addition to logging to LogCat.
Logging to files has been done in Java development for ~15 years, and there is plenty of code available to demonstrate it.
You can try this code!
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -d *:V";
Log.d(TAG, "command: " + command);
try{
Process process = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try{
File file = new File(filename);
file.createNewFile();
FileWriter writer = new FileWriter(file);
while((line = in.readLine()) != null){
writer.write(line + "\n");
}
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
Ref: How to keep on appending logs while writing into File in SDCard?
i use this:
Logger logger=Logger.getLogger("myLoggerName");
logger.setLevel(Level.ALL);
File logFileDirectory=new File(getExternalFilesDir(null),"myLogDirectory");
addFileHandler(logger,logFileDirectory,"myLogFile");
I have 3 different process running and wanted to collect logs from them on to a single log file, using logcat.
Is it possible this logfile to have logs only from my 3 processes ? How to do the same programitcally.
any help regarding the same highly appreciated.
-regards,
Manju
you can try this way call this method and put put your message what you write in log file and is stored in your sd card. Any where your application tested it will create a log and you can see the details
public static void MyLog(String msg_location, String log_message) {
String messgae_location = msg_location;
String message_details = log_message;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()
+ "/mydata/LOG");
if (!dir.exists()) {
dir.mkdirs();
}
BufferedWriter bufferedWritter = null;
try {
bufferedWritter = new BufferedWriter(new FileWriter(dir
+ File.separator + "my_Log.txt", true));
String logString = null;
logString = currentDateTime1() + ": " + messgae_location + ": "
+ message_details + "\n";
bufferedWritter.write(logString);
bufferedWritter.newLine();
bufferedWritter.flush();
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
}
You can filter the logcat output by tags.
You can use regular expressions when filtering. E.g. if you have 3 tags tag1m tag2, tag3 then if your filter is tag1|tag2 you will see logcaat output tagged by tag1 and tag2 (but not tag3).
To log your messages in a file better use Log4j for android. It's also simple.