背景:
在平常的安卓framework实战开发中经常会用到logcat来抓取分析相关的日志,同时也会结合grep进行过滤相关日志。这块我们平常使用的方式一般主要是如下几个:
# 查看不同缓冲区adb logcat -b main# 主缓冲区(默认)adb logcat -b radio# 无线/电话相关adb logcat -b events# 系统事件adb logcat -b crash# 崩溃日志adb logcat -b all# 所有缓冲区#一般如果要过滤#TAG过滤logcat -s TAG#grep过滤logcat|grepTAG但是上面的这些基本命令其实在实际开发中是完全不够的,比如列举一个日志过滤场景:
需要过滤日志中多个关键字应该如何呢?
我们过滤命令是如下:
logcat|grepTAG但是这里明显只会过滤出带有TAG的关键字的日志,还有TAG1,TAG2,TAG3这些关键字呢?
所以本文分析一些高阶常用的logcat和grep命令结合使用方法。
Logcat 高级过滤技巧
1. 按优先级过滤日志
通过设置优先级级别,仅显示特定级别的日志:
adb logcat *:W 仅显示WARN级别及以上的日志- 优先级从低到高:
V(Verbose)、D(Debug)、I(Info)、W(Warning)、E(Error)、F(Fatal)。
2. 多条件组合过滤
结合标签和优先级进行精确过滤:
adb logcat MyApp:D System.err:W *:S- 显示
MyApp标签的DEBUG及以上级别日志,System.err标签的WARN级别日志,其他标签静默(*:S)。
3. 时间范围过滤
# 显示最近N行adb logcat -t100# 最近100行# 显示特定时间后的日志adb logcat -t'01-15 14:30:00.000'# 显示日志文件中的特定时间段adb logcat -T'01-15 14:30:00.000'-t'01-15 15:00:00.000'4.查看特定应用的日志(需先获取PID)
# 按进程ID过滤adb logcat --pid=1234# 按标签过滤并显示进程信息adb logcat|grep-E"\( *1234\)"adb shell pidof com.example.app adb logcat --pid=$(adb shell pidof com.example.app)Grep 高级过滤技巧
1. 正则表达式匹配
使用-E启用扩展正则表达式:
adb logcat|grep-E'VDE]/(TAG1|TAG2)'- 匹配优先级为
V、D、E的TAG1或TAG2日志。
2. 忽略大小写
使用-i选项忽略大小写:
adb logcat|grep-i myapp- 匹配
MyApp或myapp等大小写变体。
3. 显示前后行
显示匹配行的前后5行:
# 显示匹配行及上下文grep-B5"error"# 显示匹配前5行grep-A5"error"# 显示匹配后5行grep-C5"error"# 显示匹配前后各5行# 组合使用adb logcat|grep-B2 -A2"NullPointer"4. 递归搜索文件
在当前目录及其子目录中搜索:
grep-r --color=auto'test'*-r递归搜索,--color=auto高亮显示匹配内容。
5. 仅显示文件名
不显示匹配行,仅显示文件名:
grep-r -l'test'*-l仅列出包含匹配行的文件名。
logcat和grep结合使用技巧
1. 过滤特定标签和优先级
adb logcat ActivityManager:I PowerManagerService:D *:S- 仅显示
ActivityManager标签的INFO及以上级别日志,PowerManagerService标签的DEBUG及以上级别日志,其他标签静默。
2. 实时过滤特定日志
adb logcat|grep-E'MyApp|System.err'- 实时过滤包含
MyApp或System.err的日志。
这些技巧结合adb logcat和grep命令,能高效过滤和分析Android日志,帮助快速定位问题。
实时过滤并高亮
adb logcat|grep--color=auto -E"WARN|ERROR|FATAL"3.日志中排除特定内容
# 排除特定内容adb logcat|grep-v"NoiseTag"# 排除多个 TAG,用 | 分隔adb logcat|grep-v -E"NoiseTag|AnotherTag|UselessTag"# 排除多个TAG日志adb logcat|grep-vE"NoiseTag|AnotherTag|UselessTag"