2012年12月10日星期一

如何过滤 adb logcat 输出

简介

本文介绍如何在 shell 命令行中过滤 adb logcat 输出的几个小技巧。

开发当中经常看到别人的 log 如洪水般瞬间刷满了屏幕,对自己有用的信息都被淹没了,影响心情也影响效率。下面是几个我所知道的过滤方法。

1. 只显示需要的输出,白名单

最方便的当然是通过管道使用 grep 过滤了,这样可以使用 grep 强大的正则表达式匹配。简单的匹配一行当中的某个字符串,例如 MyApp:

adb logcat | grep MyApp
adb logcat | grep -i myapp #忽略大小写。
adb logcat | grep --color=auto -i  myapp #设置匹配字符串颜色。更多设置请查看 grep 帮助。

进阶一点可以使用 grep 的正则表达式匹配。例如上一个例子会匹配一行中任意位置的 MyApp,可以设置为仅匹配 tag。默认的 log 输出如下,如果修改过输出格式相应的表达式也要修改。

I/CacheService(  665): Preparing DiskCache for all thumbnails.

可以看出 tag 是一行开头的第三个字符开始,根据这点写出表达式:

adb logcat | grep "^..MyApp"

2012年12月9日星期日

Filtering adb logcat output

Summary: This post shows several useful tips of viewing adb logcat output in shell command line.

When debugging, I usually find my screen be flooded by useless logs printed by someone else, and the logs that are useful to me are washed out at the same time. It really sucks. So I want to share some tips that I know for filtering the logs.

Please read Android official documentation Reading and Writing Logs first, which introduce the usage of the build-in filter of adb. It can filter logs by tags and by priority. If you prefer GUI, please refer to Using DDMS, which also provides the same filter.

An alternative way of filtering logcat output is using grep, which is the method that I want to share in the following paragragh.

1. White list

It's very easy to filter output by grep, and we can make use of the powerful regular expression matching function. An easy example is matching a string "MyApp" in any position of a log line:

adb logcat | grep MyApp
adb logcat | grep -i myapp #Ignore case
adb logcat | grep --color=auto -i  myapp #Set color of matching string. See grep help for more details.