How to Save Logs to File?

Currently, I'm developing an app for the company I work for, a lot of my co-workers use my app, the thing is, some times crashes/errors occur and I have no way of checking the log messages so I'll like to save the log messages in a text file so when an error happens I can check the log file and get a better idea of what is causing the problem.

I don't need the log to be sent to me through e-mail, it is good enough to have the file locally on the phone so I can plug it in my pc and extract the log file.

Currently, this is how I manage my logs:


try {
        //stuff...
    }
catch (Exception ex) {
        Log.e("Error", ex.getMessage());
    }

The Log.e("Error", ex.getMessage()); is what I would like to save.

1

2 Answers

try this :

public void appendLog(String text)
{       
 File logFile = new File("sdcard/log.file");
 if (!logFile.exists())
 {
   try
  {
     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)); 
  buf.append(text);
  buf.newLine();
  buf.close();
}
catch (IOException e)
{
  // TODO Auto-generated catch block
  e.printStackTrace();
}
}

If you do not want to change your app, you can try mmlog tool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest