Android应用logcat时间过滤失效,导出诊断日志为空问题排查
问题分析与解决方案
核心问题点
- 日期格式不匹配:你使用的
SimpleDateFormat格式字符串是MM-dd HH:mm:ss.mmm,其中mmm代表月份缩写(如May),而logcat的-T参数要求的毫秒格式是SSS,格式错误导致时间过滤完全失效。 - 命令参数解析错误:直接拼接带单引号的字符串传给
Runtime.exec(),会因为Shell的参数拆分规则,导致-T后的时间参数被错误拆分,无法被logcat正确识别。 - 时间戳有效性未校验:若
getAppLifecycleStartTime()返回的不是毫秒级时间戳(比如是秒级),生成的时间会与logcat日志时间完全不匹配。
修复后的代码
private fun executeDiagnosticLogs(tempFile: File) { // 修正为logcat要求的时间格式:MM-dd HH:mm:ss.SSS val sdf = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.getDefault()) var appStartTimestamp = sharedPreferenceManager.getAppLifecycleStartTime() // 校验时间戳有效性,避免无效值导致过滤失败 if (appStartTimestamp <= 0) { appStartTimestamp = System.currentTimeMillis() - 3600 * 1000 // 默认取当前时间前1小时 } val startTime = sdf.format(Date(appStartTimestamp)) // 用参数数组传递命令,规避Shell解析引号的问题 val cmd = arrayOf( "logcat", "$DIAG_TAG:*", "*:S", "-T", startTime, "-f", tempFile.absolutePath ) Runtime.getRuntime().exec(cmd) }
额外验证步骤
- 手动在adb shell执行命令:
logcat DIAG_TAG:* *:S -T '05-17 15:15:32.000',确认能输出对应时间后的日志,排除logcat本身的规则问题。 - 打印
startTime的值,确认格式严格符合MM-dd HH:mm:ss.SSS,比如05-17 15:15:32.000,无格式错误。
内容的提问来源于stack exchange,提问作者Wojtek K
相关产品推荐
相关产品推荐

