adb 命令使用之抓取log并过滤
转载
原文地址:http://www.2cto.com/kf/201502/376365.html
开发过程中,解决各种问题bug,不管是性能问题还是ANR问题,还是各种严重崩溃问题,经常需要抓取log,从log中分析找到问题源头,并进行修改。
但是,统一时间点下,可能会有很多log打印出来,分属于各个不同的进程。因此,我们需要的部分可能已经被淹没了。因此,使用工具或者命令抓取需要的log部分,并尽可能少的减少遗漏,是非常有必要的。
通常情况下,可以使用工具。
因此,使用命令抓取变得很重要,这里就自己总结下adb相关的命令。
比如eclipse 的logcat可以直接查看log输出,但是有个问题就是在手机设备没有连接的情况下,是很恼火的。比如我需要开机log,可以直接使用adb抓取到txt文件中就OK了。google的同时自己整理了一下。不喜勿喷。
adb logcat 命令使用帮助说明;
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | logcat: option requires an argument -- vUnrecognized OptionUsage: logcat [options] [filterspecs]options include:  -s              Set defaultfilter to silent.                  Like specifying filterspec '*:s'  -f <filename>   Log to file. Default to stdout  -r [<kbytes>]   Rotate log every kbytes. (16ifunspecified). Requires -f  -n <count>      Sets max number of rotated logs to <count>, default4  -v <format>     Sets the log print format, where <format> is one of:                  brief process tag thread raw time threadtime long  -c              clear (flush) the entire log and exit  -d              dump the log and then exit (don't block)  -t <count>      print only the most recent <count> lines (implies -d)  -g              get the size of the log's ring buffer and exit  -b <buffer>     Request alternate ring buffer, 'main', 'system', 'radio'                  or 'events'. Multiple -b parameters are allowed and the                  results are interleaved. The defaultis -b main -b system.  -B              output the log in binaryfilterspecs are a series of   <tag>[:priority]where <tag> is a log component tag (or * forall) and priority is:  V    Verbose  D    Debug  I    Info  W    Warn  E    Error  F    Fatal  S    Silent (supress all output)'*'means '*:d'and <tag> by itself means <tag>:vIf not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS.If no filterspec is found, filter defaults to '*:I'If not specified with -v, format is set from ANDROID_PRINTF_LOGor defaults to "brief"</tag></tag></tag></tag></buffer></count></count></format></format></count></count></kbytes></filename> | 
抓取log之前先清除缓存的log信息。
| 1 2 | appledeMacBook-Pro:~ apple$ adb logcat -c appledeMacBook-Pro:~ apple$ | 
或者你可以这样写
| 1 2 3 4 5 | appledeMacBook-Pro:~ apple$ adb logcat -c && adb logcat --------- beginning of /dev/log/mainE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message H | 
这样查看晕死。。。。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | appledeMacBook-Pro:~ apple$ adb logcat --------- beginning of /dev/log/mainD/AppOps  ( 1989): startOperation: allowing code 40uid 1000packageandroidD/NtpTrustedTime( 1989): currentTimeMillis() cache hit--------- beginning of /dev/log/systemD/PowerManagerService( 1989): newScreenState = 0D/PowerManagerService( 1989): updateDisplayPowerStateLocked:  mBootCompleted = true, mScreenBrightnessSettingDefault = 165D/PowerManagerService( 1989): updateDisplayPowerStateLocked:  xxxx = 187D/PowerManagerService( 1989): Package Lib: shouldUseProximitySensorLocked mLidMode = falseD/PowerManagerService( 1989): updateDisplayPowerStateLocked:  yyyyy = 187D/PowerManagerDisplayController( 1989):  changed is false, mPendingRequestChangedLocked = falseD/NtpTrustedTime( 1989): currentTimeMillis() cache hitD/NtpTrustedTime( 1989): currentTimeMillis() cache hit | 
使用I,V,D,E,F,W等过滤
和Log.i ,Log.e ,Log.d,Log.w等对应。
| 1 2 3 4 5 6 7 8 9 10 11 12 | appledeMacBook-Pro:~ apple$ adb logcat *:I --------- beginning of /dev/log/main--------- beginning of /dev/log/systemE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message HE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message HE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message H | 
上面输出全部是Log.i打印出来的Log.
输出指定标签的日志.后面必须是*:S
| 1 2 3 4 | appledeMacBook-Pro:~ apple$ adb logcat Wisdom_ConnectSdk:* *:S--------- beginning of /dev/log/main--------- beginning of /dev/log/systemI/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200 | 
打印有时间的Log
| 1 2 3 4 5 6 7 8 9 | appledeMacBook-Pro:~ apple$ adb logcat -v time--------- beginning of /dev/log/main02-0812:18:48.700D/eup     (17972): rqdp{  current unseen pn:}com.tencent.androidqqmail:Push02-0812:18:49.810D/MSF.C.NetConnTag( 2700): [E]netRecv ssoSeq:2023997818uin:*9889cmd:-316037937202399809802-0812:18:49.840D/Q.msg.TroopMsgProxy(18335): [E]insertToList MessageRecord=friendUin:2824senderuin:9517,istroop:1,msgType:-1000,time:1423369131,shmsgseq:3394902-0812:18:50.630D/MSF.C.NetConnTag( 2700): [E]netRecv ssoSeq:2024000051uin:*9889cmd:961141751202400063502-0812:18:50.665D/MSF.C.NetConnTag( 2700): [E]pa ok: 9323902-0812:18:50.670D/MSF.C.NetConnTag( 2700): [E]netSend ssoSeq:93239uin:*9889cmd:-18366571793419--------- beginning of /dev/log/system | 
-v 设置log的打印格式。上面的time显示时间。
process 只显示进程id
| 1 2 3 4 5 6 | appledeMacBook-Pro:~ apple$ adb logcat -cappledeMacBook-Pro:~ apple$ adb logcat -v process--------- beginning of /dev/log/mainE(16917) receive a heartbeat msg: H!  (cynicok)I(16917) request longconnection success and the state = 200(Wisdom_ConnectSdk)I(16917) receive the heart message H  (Wisdom_ConnectSdk) | 
-v tag按照标签来打印。
| 1 2 3 4 5 6 7 8 9 | appledeMacBook-Pro:~ apple$ adb logcat -v tag--------- beginning of /dev/log/mainE/cynicok : receive a heartbeat msg: H!I/Wisdom_ConnectSdk: request longconnection success and the state = 200I/Wisdom_ConnectSdk: receive the heart message HI/System.out: AsyncExecImpl : add task, s = 1D/SyncMainManager: requestInstantSync check local data : quickReply--------- beginning of /dev/log/systemD/ActivityManager: Not moving, persistent: ProcessRe | 
-v thread 显示 I ,D E等日志类型,16917:16936 进程ID:线程ID
| 1 2 3 4 5 6 7 8 9 10 | appledeMacBook-Pro:~ apple$ adb logcat -v thread--------- beginning of /dev/log/mainE(16917:16936) receive a heartbeat msg: H!I(16917:16917) request longconnection success and the state = 200I(16917:16917) receive the heart message HI( 2235: 2235) AsyncExecImpl : add task, s = 1D( 2235:20109) requestInstantSync check local data : quickReply--------- beginning of /dev/log/systemD( 1989: 3972) Not moving, persistent: ProcessRecord{41fd2488 2173:com.android.phone/1001}D( 1989: 2186) noteOperation: allowing code 14uid 10042packagecom.meizu.mzsyncservice | 
根据进程id来过滤。
adb logcat | grep PID
adb logcat | grep --color= auto PID
| 1 2 3 4 5 6 7 | appledeMacBook-Pro:~ apple$ adb logcat | grep 16917E/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message HE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message H | 
带颜色的Log
| 1 2 3 4 5 | appledeMacBook-Pro:~ apple$ adb logcat | grep --color=auto  16917E/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message HE/cynicok (16917): receive a heartbeat msg: H! | 
先查看程序进程pid。下面这个命令也可以看到该进程使用内存相关情况。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | appledeMacBook-Pro:~ apple$ adb shell dumpsys meminfo com.wisdom.wisdomappApplications Memory Usage (kB):Uptime: 14917420Realtime: 24328990** MEMINFO in pid 16835[com.wisdom.wisdomapp] **                   Pss  Private  Private  Swapped     Heap     Heap     Heap                 Total    Dirty    Clean    Dirty     Size    Alloc     Free                ------   ------   ------   ------   ------   ------   ------  Native Heap        00002239620994653  Dalvik Heap    2681426660002922828344884 Dalvik Other     1603151200        Stack       242400    Other dev        4040     .so mmap     112573200    .apk mmap        5000    .ttf mmap        0000    .dex mmap      3072800   Other mmap       10800      Unknown    202462024000        TOTAL    50138492044051624493381537 | 
查看当前系统中正在跑的service
| 1 2 3 4 5 6 7 8 | appledeMacBook-Pro:~ apple$ adb shell serviceUsage: service [-h|-?]       service list       service check SERVICE       service call SERVICE CODE [i32 INT | s16 STR] ...Options:   i32: Write the integer INT into the send parcel.   s16: Write the UTF-16string STR into the send parcel. | 
列出service
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | appledeMacBook-Pro:~ apple$ adb shell service listFound 92services:0secsystemserver: [com.lbe.security.service.core.loader2.internal.ISystemServer]1secloader2: [com.lbe.security.service.core.loader2.internal.ILoaderServiceEx]2sip: [android.net.sip.ISipService]3phone_ext: [com.meizu.telephony.ITelephonyExt]4phone: [com.android.internal.telephony.ITelephony]5iphonesubinfo: [com.android.internal.telephony.IPhoneSubInfo]6simphonebook: [com.android.internal.telephony.IIccPhoneBook]7isms: [com.android.internal.telephony.ISms]8gesture_manager: [android.view.IGestureManager]9deivce_states: [android.os.IDeviceStateService]10access_control: [android.content.IAccessControlManager]11media_router: [android.media.IMediaRouterService]12print: [android.print.IPrintManager]13dreams: [android.service.dreams.IDreamManager] | 
有人写了个脚本查看log,具体地址忘了,怪我只保存了脚本内容,却把来源忘了。
python值得学习。有空是要学习下。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/usr/bin/env python#coding:utf-8#This script is aimed to grep logs by application(User should input a packageName and then we look up forthe process ids then separate logs by process ids).importosimportsyspackageName=str(sys.argv[1])command = "adb shell ps | grep %s | awk '{print $2}'"%(packageName)p = os.popen(command)##forsome applications,there are multiple processes,so we should get all the process idpid = p.readline().strip()filters = pidwhile(pid != ""):    pid = p.readline().strip()    if(pid != ''):        filters = filters +  "|"+ pid        #print 'command = %s;filters=%s'%(command, filters)if(filters != '') :    cmd = 'adb logcat | grep --color=always -E "%s" '%(filters)    os.system(cmd) | 
脚本使用:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | appledeMacBook-Pro:Desktop apple$ python logcat.py com.wisdom.wisdomappE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message HE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message HE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message HE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200I/Wisdom_ConnectSdk(16917): receive the heart message HE/cynicok (16917): receive a heartbeat msg: H!I/Wisdom_ConnectSdk(16917): request longconnection success and the state = 200 | 
ps命令过滤查看。
| 1 2 3 4 | appledeMacBook-Pro:Desktop apple$ adb shellshell@mx2:/ $ ps | grep com.meizu.flyme.weathersystem    9175156788020832432ffffffff 00000000S com.meizu.flyme.weathershell@mx2:/ $ | 
adb 这么多命令,我该快速的用呢。其实早就有大神解决了这个问题。
git 地址 :https://github.com/JakeWharton/pidcat
这个开源代码pidcat在mac上面使用需要安装HomeView
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | ^CappledeMacBook-Pro:Desktop apple$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"==> This script will install:/usr/local/bin/brew/usr/local/Library/.../usr/local/share/man/man1/brew.1Press RETURN to continueor any other key to abort==> /usr/bin/sudo /bin/mkdir /usr/localPassword:==> /usr/bin/sudo /bin/chmod g+rwx /usr/local==> /usr/bin/sudo /usr/bin/chgrp admin /usr/local==> /usr/bin/sudo /bin/mkdir /Library/Caches/Homebrew==> /usr/bin/sudo /bin/chmod g+rwx /Library/Caches/Homebrew==> Downloading and installing Homebrew...remote: Counting objects: 229812, done.remote: Compressing objects: 100% (60244/60244), done.remote: Total 229812(delta 168312), reused 229812(delta 168312)Receiving objects: 100% (229812/229812), 52.82MiB | 1022KiB/s, done.Resolving deltas: 100% (168312/168312), done.From https://github.com/Homebrew/homebrew * [newbranch]      master     -> origin/masterHEAD is now at 9a0fbf6 moreutils: update 0.55bottle.==> Installation successful!==> Next stepsRun `brew doctor` before you install anythingRun `brew help` to get startedappledeMacBook-Pro:Desktop apple$ | 
截取:
Viewing Alternative Log Buffers
Android日志系统为日志消息保持了多个循环缓冲区,而且不是所有的消息都被发送到默认缓冲区,要想查看这些附加的缓冲区,可以使用-b 选项,以下是可以指定的缓冲区:
radio — 查看包含在无线/电话相关的缓冲区消息
events — 查看事件相关的消息
main — 查看主缓冲区 (默认缓冲区)
-b 选项的用法:
| 1 | [adb] logcat [-b <buffer>]</buffer> | 
例如查看radio缓冲区:
| 1 | adb logcat -b radio | 
保存Log到sd卡。
| 1 2 | appledeMacBook-Pro:~ apple$ adb logcat -d -f /sdcard/test_log.txtappledeMacBook-Pro:~ apple$ | 
配置adb环境变量,并且将变量添加到.bashrc or .zshrc 两个文件中
| 1 | export PATH=$PATH:/Users/apple/Documents/Tools/IDE/adt-bundle-mac-x86_64-20131030/sdk/tools:/Users/apple/Documents/Tools/IDE/adt-bundle-mac-x86_64-20131030/sdk/platform-tools | 
并且要保证.bash_profile也配置好adb。

安装完成HomeView以及配置好环境后,安装pidcat.py
| 1 2 3 | appledeMacBook-Pro:Desktop apple$ brew install pidcat==> Downloading https://github.com/JakeWharton/pidcat/archive/1.4.1.tar.gz######################################################################## 100.0% | 
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号