Skip to content

Instantly share code, notes, and snippets.

@vaibhav-jani
Created May 10, 2022 04:30
Show Gist options
  • Select an option

  • Save vaibhav-jani/c542f6fddcdf0a3f4a41a27ae59d0604 to your computer and use it in GitHub Desktop.

Select an option

Save vaibhav-jani/c542f6fddcdf0a3f4a41a27ae59d0604 to your computer and use it in GitHub Desktop.
Text file logger Android
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