Created
January 31, 2018 21:13
-
-
Save rockaport/35405db45ac54725c57403ecb5057be6 to your computer and use it in GitHub Desktop.
This file contains 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
package com.sample.crashlogger | |
import android.content.Context | |
import android.os.Environment | |
import android.util.Log | |
import org.apache.commons.io.FileUtils | |
import org.apache.commons.lang.exception.ExceptionUtils | |
import java.io.File | |
import java.io.IOException | |
import java.nio.charset.StandardCharsets | |
import java.text.SimpleDateFormat | |
import java.util.* | |
private val tag = "CrashLogger" | |
private val directoryName = "/crash-logs" | |
private val iso8601DateFormat = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US) | |
object CrashLogger { | |
var initialized = false | |
lateinit var logDirectory: File | |
private lateinit var applicationId: String | |
private lateinit var applicationVersion: String | |
private val defaultUncaughtExceptionHandler: Thread.UncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler() | |
fun initialize(context: Context) { | |
if (initialized) return | |
logDirectory = File(context.filesDir, directoryName) | |
applicationId = context.packageName | |
applicationVersion = context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "1" | |
Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> | |
logToDirectory(throwable) | |
defaultUncaughtExceptionHandler.uncaughtException(thread, throwable) | |
} | |
initialized = true | |
} | |
fun logToDirectory(throwable: Throwable) { | |
val fileName = "$applicationId-" + | |
"v$applicationVersion-" + | |
"crash-" + | |
"${iso8601DateFormat.format(Date())}.txt" | |
val outputFile = File(logDirectory, fileName) | |
try { | |
FileUtils.write(outputFile, ExceptionUtils.getStackTrace(throwable), StandardCharsets.UTF_8) | |
} catch (e: IOException) { | |
Log.e(tag, "Failed to write crash log file: $fileName", e) | |
} | |
} | |
fun export() { | |
val externalLogDir = File( | |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), | |
directoryName) | |
try { | |
FileUtils.copyDirectory(logDirectory, externalLogDir) | |
logDirectory.listFiles().filter { !it.isDirectory }.forEach { it.delete() } | |
} catch (e: IOException) { | |
Log.e(tag, "Failed to export log files", e) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment