How to write log to sd card in Android? [duplicate]

旧街凉风 提交于 2019-12-04 09:21:41
Shini

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.

Himanshu Agarwal

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!