Home > Blockchain >  How do I save app logs locally on Android?
How do I save app logs locally on Android?

Time:07-25

I want to save the logs generated by my application locally on the android device and view them in an instance of a crash. Using the "Take Bug Report" under the developer options gives the entire system logs which are irrelevant to me. I am looking only for those logs created by my application when it runs. Is there any application that does this? Or are there any libraries I could include in my application code to satisfy my requirement?

CodePudding user response:

You may just add firebase to your project, and everything will be done automatically.
Or if need it to be "locally", can use the Thread.UncaughtExceptionHandler to save crash log. Register it when your application onCreate.

private static UncaughtExceptionHandler mDefaultUncaughtExceptionHandler;

public static void registerUncaughtExceptionHandler() {
    mDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable ex) {
            // Save Log
            saveLog(ex);

            // Throw system
            mDefaultUncaughtExceptionHandler.uncaughtException(thread, ex);
        }
    });
}

private static void saveLog(Throwable exception) {
    try {
        String stackTrace = Log.getStackTraceString(exception);
        // Save it to SharedPreferences or DB as you like
    } catch (Exception e) {
    }
}

Then can extract the last crash log, submit to your server or display in logcat when app starts.

CodePudding user response:

It is much better to use Third Party libraries such as Firebase Crashlytics or Sentry Crash Report or AppMetrica for crash reports. just add these libraries and make an account on one of these sites, then you can have a full report of crashes if happen. but if you want to save the logs on the device, you can refer to this question :

Saving Logcat to a text file in Android Device

CodePudding user response:

You can try this

   fun writeLog(context: Context) {
        try {
            val path = File(context.filesDir, "log_files")
            if (!path.exists()) {
                path.mkdir()
            }

            val fileName = "your_filename.txt"

            Runtime.getRuntime().exec("logcat -v time -f $fileName")
        } catch (e: IOException) {

        }
    }

Or you can change logcat command based on your requirements: refer to this https://developer.android.com/studio/command-line/logcat

You can check it at data/data/{applicationId}/files/log_files/

  • Related