他山之石(2)—— Timber 如何实现默认打tag的

https://github.com/JakeWharton/timber 官方地址在这里

普通打印, 需要输入tag

Log.d("MainActivity","this is gerry!")

Timber 打印

Timber.d("this is gerry!")

打印如下: 这个MainActivity是如何打印出来的呢?

00:07:20.632 10659-10659 MainActivity     D  this is gerry!
override val tag: String?
      get() = super.tag ?: Throwable().stackTrace // 直接获取当前堆栈
        .first { it.className !in fqcnIgnore } // 取第一行非Timber代码的堆栈信息
        .let(::createStackElementTag)

private val fqcnIgnore = listOf(
      Timber::class.java.name,
      Forest::class.java.name,
      Tree::class.java.name,
      DebugTree::class.java.name
    )

private const val MAX_TAG_LENGTH = 23
private val ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$")
      
protected open fun createStackElementTag(element: StackTraceElement): String? {
      var tag = element.className.substringAfterLast('.') // 取最后一个.后面的类名
      val m = ANONYMOUS_CLASS.matcher(tag)  // 类有可能是匿名内部类会有$符号,所以要替换成外部类
      if (m.find()) {
        tag = m.replaceAll("")
      }
      // Tag length limit was removed in API 26.
      return if (tag.length <= MAX_TAG_LENGTH || Build.VERSION.SDK_INT >= 26) {
        tag
      } else {
        tag.substring(0, MAX_TAG_LENGTH)
      }
    }

你可能感兴趣的:(源码分析,Timber,日志库,默认TAG,堆栈信息)