Jetpack Compose中Timber日志随设备旋转重复累积问题求助
问题:Jetpack Compose中Timber旋转日志重复递增问题
在Jetpack Compose中使用Timber输出日志时,遇到设备旋转后日志数量逐次递增的异常:第一次旋转生成1条日志,第二次生成2条,以此类推。将Timber替换为系统Log类后,重复日志问题消失。想确认这是Timber的已知问题还是自身操作有误?
响应旋转的Composable代码
@Composable fun OrientationListener(onPortrait: () -> Unit, onLandscape: () -> Unit) { var previousOrientation by rememberSaveable { mutableIntStateOf(Configuration.ORIENTATION_UNDEFINED) } val configuration = LocalConfiguration.current // 监听方向变化并触发对应回调 LaunchedEffect(configuration.orientation) { if (previousOrientation != configuration.orientation) { Log.d(TAG,"########## ORIENTATION previousOrientation: $previousOrientation current configuration: ${configuration.orientation}###############") previousOrientation = configuration.orientation val isPortrait = configuration.orientation == Configuration.ORIENTATION_PORTRAIT if (isPortrait) { onPortrait() } else { onLandscape() } } } }
将上述代码中的Log.d替换为Timber.d后,控制台会打印多条重复日志。
Timber初始化代码(MainActivity中)
if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree())
分析与解决
这个问题并非Timber的已知问题,核心原因是初始化逻辑不当:
- 问题根源:设备旋转时Activity会重建,如果
Timber.plant(Timber.DebugTree())写在Activity的onCreate方法中,每次旋转都会重新种植一棵DebugTree。Timber的Tree实例是累加存储的,每多一棵Tree,同一条日志就会被多打印一次,因此日志数量会随旋转次数递增。 - 对比
Log类:系统Log没有Tree累加机制,每次调用都是直接输出,因此不会出现重复日志。
修复方案
确保Timber的初始化全局仅执行一次,有两种常见实现方式:
- 自定义Application类初始化
创建自定义Application类,在其onCreate方法中完成Timber初始化:
class MyApp : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } }
然后在AndroidManifest.xml中指定该Application:
<application android:name=".MyApp" <!-- 其他配置 --> > <!-- Activity等组件配置 --> </application>
- Activity内加判断避免重复种植
如果不想自定义Application,可在MainActivity的onCreate中添加判断,仅当没有已种植的Tree时才执行初始化:
if (BuildConfig.DEBUG && Timber.treeCount() == 0) { Timber.plant(Timber.DebugTree()) }
内容的提问来源于stack exchange,提问作者user1553131
相关产品推荐
相关产品推荐

