Created
May 10, 2022 04:30
-
-
Save vaibhav-jani/c542f6fddcdf0a3f4a41a27ae59d0604 to your computer and use it in GitHub Desktop.
Text file logger Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.content.Context | |
| import io.reactivex.Completable | |
| import io.reactivex.schedulers.Schedulers | |
| import timber.log.Timber | |
| import java.io.BufferedWriter | |
| import java.io.File | |
| import java.io.FileWriter | |
| import java.io.IOException | |
| object TextFileLogger { | |
| fun appendLog(text: String, context: Context) { | |
| Completable.fromCallable { | |
| val path = context.filesDir; | |
| val file = File(path, "text_logger.txt") | |
| if (!file.exists()) { | |
| try { | |
| file.createNewFile() | |
| } catch (e: IOException) { | |
| e.printStackTrace() | |
| } | |
| } | |
| try { | |
| //BufferedWriter for performance, true to set append to file flag | |
| val buf = BufferedWriter(FileWriter(file, true)) | |
| buf.append(text) | |
| buf.newLine() | |
| buf.close() | |
| } catch (e: IOException) { | |
| e.printStackTrace() | |
| } | |
| }.subscribeOn(Schedulers.io()) | |
| .subscribe( | |
| { | |
| Timber.v("Logging done: $text" ) | |
| }, | |
| { | |
| it.printStackTrace() | |
| Timber.v("Logging failed: $text") | |
| } | |
| ) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment