Skip to content

Instantly share code, notes, and snippets.

@RareScrap
Created September 1, 2021 08:26
Show Gist options
  • Save RareScrap/28378cfe9f9850d1157f905cc12b27f8 to your computer and use it in GitHub Desktop.
Save RareScrap/28378cfe9f9850d1157f905cc12b27f8 to your computer and use it in GitHub Desktop.
import android.content.Context
import java.io.File
import java.io.FileOutputStream
import java.io.PrintWriter
import java.io.StringWriter
fun Context.logToFile(str: String, filename: String = "LOG.txt") {
val file = File("$filesDir${File.separator}$filename")
if (!file.exists()) file.createNewFile()
FileOutputStream(file, true).bufferedWriter().use { out -> out.appendLine(str) }
}
fun Context.logToFile(exception: Exception) {
logToFile(getStackTraceString(exception))
}
fun getStackTraceString(tr: Throwable?): String {
var t = tr
while (t != null) {
t = t.cause
}
val sw = StringWriter()
val pw = PrintWriter(sw)
tr?.printStackTrace(pw)
pw.flush()
return sw.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment