Created
January 15, 2018 11:14
-
-
Save whalemare/701d0f121a341d032999c5d0a7ed5dc2 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
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