StagingDebug模式下Timber日志未在Debug Console/Logcat输出求助
这种情况我碰到过好几次,大概率是Timber的初始化环节出了问题,或者你的StagingDebug构建变体没被正确配置到Timber的日志逻辑里。给你拆解几个最可能的遗漏点:
Timber不是开箱即用的,必须在App启动时调用Timber.plant()添加日志树(Tree)才能输出日志。你可能只在默认的Debug变体里做了初始化,但StagingDebug作为自定义变体没触发这段逻辑。
举个标准的初始化示例:
class MyApp : Application() { override fun onCreate() { super.onCreate() // 根据构建变体选择对应日志树 if (BuildConfig.DEBUG) { // DebugTree会原样输出所有日志级别 Timber.plant(Timber.DebugTree()) } else { // 生产环境通常用自定义Tree过滤日志级别或上报到监控平台 Timber.plant(ReleaseTree()) } } }
这里要重点确认:你的StagingDebug变体的BuildConfig.DEBUG是否为true?如果在build.gradle里把StagingDebug的buildType设成了release,那BuildConfig.DEBUG会是false,就会走ReleaseTree——而ReleaseTree通常会过滤掉Info级别的日志。
如果你的StagingDebug是Flavor+BuildType的组合(比如Flavor为Staging,BuildType为Debug),那可能你只针对默认的Debug buildType做了初始化,没考虑Flavor的组合情况。
你可以通过BuildConfig的参数精准判断变体:
// 只针对StagingDebug初始化DebugTree if (BuildConfig.BUILD_TYPE == "debug" && BuildConfig.FLAVOR == "staging") { Timber.plant(Timber.DebugTree()) } // 或者更灵活:所有Debug类型的构建(不管Flavor)都初始化DebugTree if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) }
同时要确保build.gradle里Staging对应的buildType配置了debuggable true:
android { buildTypes { debug { debuggable true // 其他Debug配置 } release { debuggable false // 其他Release配置 } } productFlavors { staging { // Staging风味的自定义配置 } production { // Production风味的自定义配置 } } }
这样StagingDebug组合出来的变体,debuggable为true,BuildConfig.DEBUG也会是true,就能触发Timber的DebugTree初始化。
如果你的StagingDebug不小心用了ReleaseTree(比如BuildConfig.DEBUG为false),而自定义的ReleaseTree可能只允许Error/Warn级别的日志,那Timber.i()自然不会输出。比如你的ReleaseTree可能是这样:
class ReleaseTree : Timber.Tree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { // 只输出Error及以上级别的日志 if (priority >= Log.ERROR) { // 上报到监控平台的逻辑 } } }
这种情况下Info级别的日志会被直接忽略,自然看不到输出。
确保build.gradle里已经引入了Timber的依赖,且不是只在特定变体下引入:
dependencies { implementation 'com.jakewharton.timber:timber:5.0.1' // 不要写成debugImplementation,除非你确认所有Debug变体都能继承这个依赖 }
总结排查步骤
- 检查Application类中是否调用了
Timber.plant(),且StagingDebug变体能触发DebugTree的初始化; - 确认StagingDebug的
build.gradle配置中debuggable为true,BuildConfig.DEBUG值正确; - 排查自定义ReleaseTree的日志级别过滤规则;
- 确认Timber依赖已正确引入所有需要的变体。
内容的提问来源于stack exchange,提问作者Expert wanna be

