Skip to content

Instantly share code, notes, and snippets.

@xvadsan
Created November 1, 2020 13:10
Show Gist options
  • Save xvadsan/c82ac2e127578ef3666fa43363ff086d to your computer and use it in GitHub Desktop.
Save xvadsan/c82ac2e127578ef3666fa43363ff086d to your computer and use it in GitHub Desktop.
Log handler. Writing logs to a file via Timber.
import android.os.Build
import android.os.Environment
import android.util.Log
import org.threeten.bp.LocalDateTime
import tech.dcloud.erfid.core.base.extension.getDateTimeOfPattern
import tech.dcloud.erfid.ugrokit.BuildConfig
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
class LoggerHandler : Timber.Tree() {
private val formatter = LocalDateTime.now().getDateTimeOfPattern("dd_LL_YYYY_HH_mm_ss")
private var versionName = "0"
private var versionCode = 0
init {
versionName = BuildConfig.VERSION_NAME
versionCode = BuildConfig.VERSION_CODE
}
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority == Log.ERROR) {
try {
val dumpDate = Date(System.currentTimeMillis())
val reportBuilder = StringBuilder()
reportBuilder
.append("\n\n\n")
.append("LogException").append("\n")
.append(formatter.format(dumpDate)).append("\n")
.append(String.format("Version: %s (%d)\n", versionName, versionCode))
.append("Device: ${Build.BRAND} ${Build.MODEL}\n")
.append("Android ${Build.VERSION.SDK_INT}(API)\n")
processThrowable(t, reportBuilder)
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
if (!path.exists()) path.mkdirs()
val file = File(path, TXT_NAME)
if (file.exists().not()) file.createNewFile()
val fos = FileOutputStream(file, true)
fos.use { it.write(reportBuilder.toString().toByteArray(Charsets.UTF_8)) }
fos.use { it.flush() }
fos.use { it.close() }
} catch (e: IOException) {
Log.println(Log.ERROR, "FileLogTree", "Error while logging into file: $e")
}
}
}
private fun processThrowable(exception: Throwable?, builder: StringBuilder) {
if (exception == null)
return
val stackTraceElements = exception.stackTrace
builder
.append("Exception: ").append(exception.javaClass.name).append("\n")
.append("Message: ").append(exception.message).append("\nStacktrace:\n")
for (element in stackTraceElements) {
builder.append("\t").append(element.toString()).append("\n")
}
processThrowable(exception.cause, builder)
}
companion object {
const val TXT_NAME = "ERFID_log.txt"
}
}
@xvadsan
Copy link
Author

xvadsan commented Nov 1, 2020

implementation 'com.jakewharton.timber:timber:4.7.1'

in App in onCreate:
Timber.plant(DebugTree())
Timber.plant(LoggerHandler())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment