Skip to content

Instantly share code, notes, and snippets.

@whalemare
Created January 15, 2018 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whalemare/701d0f121a341d032999c5d0a7ed5dc2 to your computer and use it in GitHub Desktop.
Save whalemare/701d0f121a341d032999c5d0a7ed5dc2 to your computer and use it in GitHub Desktop.
class TimberLinkingTree : Timber.Tree() {
private val CALL_STACK_INDEX = 4
private val ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$")
override fun log(priority: Int, tag: String, message: String, t: Throwable) {
val stackTrace = Throwable().stackTrace
if (stackTrace.size <= CALL_STACK_INDEX) {
throw IllegalStateException(
"Synthetic stacktrace didn't have enough elements: are you using proguard?")
}
val clazz = extractClassName(stackTrace[CALL_STACK_INDEX])
val lineNumber = stackTrace[CALL_STACK_INDEX].lineNumber
val formatted = ".($clazz.java:$lineNumber) - $message"
super.log(priority, tag, formatted, t)
}
/**
* Extract the class name without any anonymous class suffixes (e.g., `Foo$1`
* becomes `Foo`).
*/
private fun extractClassName(element: StackTraceElement): String {
var tag = element.className
val m = ANONYMOUS_CLASS.matcher(tag)
if (m.find()) {
tag = m.replaceAll("")
}
return tag.substring(tag.lastIndexOf('.') + 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment