Android系统中有哪些日志信息和工具

Android系统日志和工具



我们经常需要查看设备里面的各种日志信息。所以有必要了解android系统里面有哪些日志,以及用什么方式可以提取这些日志。以我手头的红米note4xplus为例,其基本配置为高通msm8953,android7.0。我们可以看一下根文件系统:

mido:/ # ls
acct              init.carrier.rc                      init.qcom.sh               root             
bin               init.class_main.sh                   init.qcom.syspart_fixup.sh sbin             
bt_firmware       init.environ.rc                      init.qcom.usb.rc           sdcard           
cache             init.mdm.sh                          init.qcom.usb.sh           seapp_contexts   
charger           init.miui.cust.rc                    init.rc                    selinux_version  
config            init.miui.early_boot.sh              init.recovery.hardware.rc  sepolicy         
cust              init.miui.google_revenue_share.rc    init.target.rc             service_contexts 
d                 init.miui.google_revenue_share_v2.rc init.usb.configfs.rc       storage          
data              init.miui.nativedebug.rc             init.usb.rc                sys              
default.prop      init.miui.post_boot.sh               init.zygote32.rc           system           
dev               init.miui.rc                         init.zygote64_32.rc        tombstones       
dsp               init.msm.usb.configfs.rc             mnt                        ueventd.qcom.rc  
etc               init.qcom.class_core.sh              oem                        ueventd.rc       
file_contexts.bin init.qcom.early_boot.sh              persist                    unlock_key       
firmware          init.qcom.factory.rc                 proc                       vendor           
fstab.qcom        init.qcom.rc                         property_contexts          verity_key       
init              init.qcom.sensors.sh                 res     

以这个设备的文件系统为基础,我们来看一下一般的android设备中都有那些系统日志。

本文档只做日志相关的概要说明,不具体说明每个工具的使用方法。

1 日志命令

android设备默认的命令一般都在/system/bin, /system/xbin和/sbin目录下。我们选择几个常用的命令来做个说明。

atrace

实际上就是systrace的代理。用来抓取用户空间服务日志信息。

一般用法:

adb shell atrace sched freq idle gfx view sync -b 96000 -f atrace.log

命令帮助:

adb shell atrace --help
usage: atrace [options] [categories...]
options include:
  -a appname      enable app-level tracing for a comma separated list of cmdlines
  -b N            use a trace buffer size of N KB
  -c              trace into a circular buffer
  -f filename     use the categories written in a file as space-separated
                    values in a line
  -k fname,...    trace the listed kernel functions
  -n              ignore signals
  -s N            sleep for N seconds before tracing [default 0]
  -t N            trace for N seconds [defualt 5]
  -z              compress the trace dump
  --async_start   start circular trace and return immediatly
  --async_dump    dump the current contents of circular trace buffer
  --async_stop    stop tracing and dump the current contents of circular
                    trace buffer
  --stream        stream trace to stdout as it enters the trace buffer
                    Note: this can take significant CPU time, and is best
                    used for measuring things that are not affected by
                    CPU performance, like pagecache usage.
  --list_categories
                  list the available tracing categories
 -o filename      write the trace to the specified file instead
                    of stdout.

所有的业务类型列表:

adb shell atrace --list_categories
         gfx - Graphics
       input - Input
        view - View System
     webview - WebView
          wm - Window Manager
          am - Activity Manager
          sm - Sync Manager
       audio - Audio
       video - Video
      camera - Camera
         hal - Hardware Modules
         app - Application
         res - Resource Loading
      dalvik - Dalvik VM
          rs - RenderScript
      bionic - Bionic C Library
       power - Power Management
          pm - Package Manager
          ss - System Server
    database - Database
       sched - CPU Scheduling
         irq - IRQ Events
        freq - CPU Frequency
        idle - CPU Idle
        disk - Disk I/O
         mmc - eMMC commands
        load - CPU Load
        sync - Synchronization
       workq - Kernel Workqueues
  memreclaim - Kernel Memory Reclaim
  regulators - Voltage and Current Regulators
  binder_driver - Binder Kernel driver
  binder_lock - Binder global lock trace
   pagecache - Page cache

bootstat

查看设备启动状态信息。

adb shell bootstat -p
Boot events:
------------
post_decrypt_time_elapsed	12
build_date	1567090617
boot_decryption_complete	26
ota_boot_complete_post_decrypt	182
ota_boot_complete	223
boot_reason	1
factory_reset_current_time	1656123419
factory_reset	1651199117
boot_complete_post_decrypt	14
boot_complete	26
factory_reset_record_value	1651199117
time_since_factory_reset	4924302

bugreport

bugreport是一个集大成的日志命令,会将系统中所有缓存的日志信息分门别类的导出来。

这个命令有两个版本:bugreport和bugreportz。后面命令的差别是将日志压缩成zip文件。

一般使用方式:

adb shell bugreport bugreport.log

日志导出时间很长,一般需要几分钟,日志的文件也很大,最少几十MB。

bugreport日志有多种GUI分析工具,除了battery historian之外,还有chkBugreport等工具。

debuggerd & debuggerd64

这个命令用来收集指定进程的堆栈日志信息,并将日志信息写入到/data/tombstones/tombstone_xx文件中。

一般用法:

debuggerd64 3006                                                                 
Sending request to dump task 3006.
Tombstone written to: /data/tombstones/tombstone_00

dmesg

显示内核缓冲区日志信息。

一般用法:

dmesg --help                                                                                   
usage: dmesg [-c] [-r|-t] [-n LEVEL] [-s SIZE]

Print or control the kernel ring buffer.

-c	Clear the ring buffer after printing
-n	Set kernel logging LEVEL (1-9)
-r	Raw output (with <level markers>)
-s	Show the last SIZE many bytes
-t	Don't print kernel's timestamps

dumpstate

dumpstate命令用来dump系统的运行状态信息。bugreport的报告信息实际上就是dumpstate导出的。

dumpstate --help
usage: dumpstate [-h] [-b soundfile] [-e soundfile] [-o file [-d] [-p] [-z]] [-s] [-S] [-q] [-B] [-P] [-R] [-V version]
  -h: display this help message
  -b: play sound file instead of vibrate, at beginning of job
  -e: play sound file instead of vibrate, at end of job
  -o: write to file (instead of stdout)
  -d: append date to filename (requires -o)
  -p: capture screenshot to filename.png (requires -o)
  -z: generate zipped file (requires -o)
  -s: write output to control socket (for init)
  -S: write file location to control socket (for init; requires -o and -z)  -q: disable vibrate
  -B: send broadcast when finished (requires -o)
  -P: send broadcast when started and update system properties on progress (requires -o and -B)
  -R: take bugreport in remote mode (requires -o, -z, -d and -B, shouldn't be used with -P)
  -V: sets the bugreport format version (valid values: 1.0)

dumpsys

dumpsys命令用来dump所有运行的服务状态信息。

dumpsys --help
usage: dumpsys
         To dump all services.
or:
       dumpsys [-t TIMEOUT] [--help | -l | --skip SERVICES | SERVICE [ARGS]]
         --help: shows this help
         -l: only list services, do not dump them
         -t TIMEOUT: TIMEOUT to use in seconds instead of default 10 seconds
         --skip SERVICES: dumps all services but SERVICES (comma-separated list)
         SERVICE [ARGS]: dumps only service SERVICE, optionally passing ARGS to it

dumpsys -l
Currently running services:
  DisplayFeatureControl
  DockObserver
  MiuiBackup
  MiuiInit
  ProcessManager
  SurfaceFlinger
  accessibility
  account
  activity
  alarm
  android.hardware.fingerprint.IFingerprintDaemon
  android.security.keystore
  android.service.gatekeeper.IGateKeeperService
  android.vendor.fido.IFidoDaemon
  appops
  appwidget
  assetatlas
  audio
  backup
  battery
  batteryproperties
  batterystats
  bluetooth_manager
  carrier_config
  clipboard
  cneservice
  com.qualcomm.location.izat.IzatService
  com.qualcomm.qti.qseeproxy
  com.xiaomi.mlipayservice
  com.xiaomi.mtservice
  com.xiaomi.vsimservice
  commontime_management
  connectivity
  connectivity_metrics_logger
  consumer_ir
  content
  contexthub_service
  country_detector
  cpuinfo
  dbinfo
  device_policy
  deviceidle
  devicestoragemonitor
  diskstats
  display
  display.qservice
  dns_listener
  dreams
  drm.drmManager
  dropbox
  ethernet
  extphone
  fingerprint
  fingerprints_service
  gfxinfo
  gpu
  graphicsstats
  hardware_properties
  imms
  ims
  input
  input_method
  iphonesubinfo
  isms
  isub
  jobscheduler
  launcherapps
  location
  locationpolicy
  lock_settings
  media.audio_flinger
  media.audio_policy
  media.camera
  media.camera.proxy
  media.codec
  media.drm
  media.extractor
  media.player
  media.radio
  media.resource_manager
  media.sound_trigger_hw
  media_projection
  media_router
  media_session
  meminfo
  midi
  miui.contentcatcher.ContentCatcherService
  miui.face.FaceService
  miui.fdpp
  miui.mqsas.IMQSNative
  miui.mqsas.MQSService
  miui.security.keystore
  miui.sedc
  miui.shell
  miui.whetstone.klo
  miui.whetstone.mcd
  miui.whetstone.power
  mount
  netd
  netpolicy
  netstats
  network_management
  network_score
  network_time_update_service
  notification
  otadexopt
  package
  perfshielder
  permission
  persistent_data_block
  phone
  pinner
  power
  print
  processinfo
  procstats
  qti.ims.connectionmanagerservice
  qti.ims.ext
  qtitetherservice
  recovery
  restrictions
  rttmanager
  samplingprofiler
  scheduling_policy
  search
  security
  sensorservice
  serial
  servicediscovery
  shortcut
  simphonebook
  sip
  soundtrigger
  statusbar
  telecom
  telephony.registry
  textservices
  trust
  uimode
  updatelock
  usagestats
  usb
  user
  vendor.qcom.PeripheralManager
  vibrator
  voiceinteraction
  vrmanager
  wallpaper
  webviewupdate
  whetstone.activity
  wifi
  wifip2p
  wifiscanner
  window
  xiaomi.joyose

logcat

最常用的日志命令。用来实时显示日志缓冲区信息。

一般用法:

logcat --help
Usage: logcat [options] [filterspecs]
options include:
  -s              Set default filter to silent.
                  Like specifying filterspec '*:S'
  -f <filename>   Log to file. Default is stdout
  --file=<filename>
  -r <kbytes>     Rotate log every kbytes. Requires -f
  --rotate-kbytes=<kbytes>
  -n <count>      Sets max number of rotated logs to <count>, default 4
  --rotate-count=<count>
  -v <format>     Sets the log print format, where <format> is:
  --format=<format>
                      brief color epoch long monotonic printable process raw
                      tag thread threadtime time uid usec UTC year zone

  -D              print dividers between each log buffer
  --dividers
  -c              clear (flush) the entire log and exit
  --clear
  -d              dump the log and then exit (don't block)
  -e <expr>       only print lines where the log message matches <expr>
  --regex <expr>  where <expr> is a regular expression
  -m <count>      quit after printing <count> lines. This is meant to be
  --max-count=<count> paired with --regex, but will work on its own.
  --print         paired with --regex and --max-count to let content bypass
                  regex filter but still stop at number of matches.
  -t <count>      print only the most recent <count> lines (implies -d)
  -t '<time>'     print most recent lines since specified time (implies -d)
  -T <count>      print only the most recent <count> lines (does not imply -d)
  -T '<time>'     print most recent lines since specified time (not imply -d)
                  count is pure numerical, time is 'MM-DD hh:mm:ss.mmm...'
                  'YYYY-MM-DD hh:mm:ss.mmm...' or 'sssss.mmm...' format
  -g              get the size of the log's ring buffer and exit
  --buffer-size
  -G <size>       set size of log ring buffer, may suffix with K or M.
  --buffer-size=<size>
  -L              dump logs from prior to last reboot
  --last
  -b <buffer>     Request alternate ring buffer, 'main', 'system', 'radio',
  --buffer=<buffer> 'events', 'crash', 'default' or 'all'. Multiple -b
                  parameters are allowed and results are interleaved. The
                  default is -b main -b system -b crash.
  -B              output the log in binary.
  --binary
  -S              output statistics.
  --statistics
  -p              print prune white and ~black list. Service is specified as
  --prune         UID, UID/PID or /PID. Weighed for quicker pruning if prefix
                  with ~, otherwise weighed for longevity if unadorned. All
                  other pruning activity is oldest first. Special case ~!
                  represents an automatic quicker pruning for the noisiest
                  UID as determined by the current statistics.
  -P '<list> ...' set prune white and ~black list, using same format as
  --prune='<list> ...'  printed above. Must be quoted.
  --pid=<pid>     Only prints logs from the given pid.
  --wrap          Sleep for 2 hours or when buffer about to wrap whichever
                  comes first. Improves efficiency of polling by providing
                  an about-to-wrap wakeup.

filterspecs are a series of 
  <tag>[:priority]

where <tag> is a log component tag (or * for all) and priority is:
  V    Verbose (default for <tag>)
  D    Debug (default for '*')
  I    Info
  W    Warn
  E    Error
  F    Fatal
  S    Silent (suppress all output)

'*' by itself means '*:D' and <tag> by itself means <tag>:V.
If no '*' filterspec or -s on command line, all filter defaults to '*:V'.
eg: '*:S <tag>' prints only <tag>, '<tag>:S' suppresses all <tag> log messages.

If not specified on the command line, filterspec is set from ANDROID_LOG_TAGS.

If not specified with -v on command line, format is set from ANDROID_PRINTF_LOG
or defaults to "threadtime"

vmstat

vmstat 命令报告关于内核线程、虚拟内存、磁盘和 CPU 活动的统计信息。

这个命令用来持续跟踪系统抖动相关的性能非常有帮助。

vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 0  0 357784 748532  13068 639784    4    9    35    16    0   61  1  1 97  0


vmstat -n 3 9
 0  0 357784 748564  13124 639792    4    8    35    15    0   61  1  1 97  0
 0  0 357784 748316  13156 639792    0    0     0    68    0  244  0  0 99  0
 0  0 357784 748316  13156 639792    0    0     0    10    0  109  0  0 100 0
 0  0 357784 748316  13164 639792    0    0     0    14    0  155  0  0 100 0
 0  0 357784 748316  13164 639792    0    0     0     0    0  132  0  0 100 0
 0  0 357784 748316  13164 639792    0    0     0    11    0  122  0  0 100 0
 0  0 357784 748316  13172 639792    0    0     0    14    0  189  0  0 100 0
 1  0 357784 748316  13172 639792    0    0     0     0    0  118  0  0 100 0
 0  0 357784 748316  13180 639792    0    0     0    14    0  120  0  0 100 0

lsof

这个命令列出当前系统打开了那些文件。

命令输出的结果非常长。

lsof --help
usage: lsof [-lt] [-p PID1,PID2,...] [NAME]...

Lists open files. If names are given on the command line, only
those files will be shown.

-l	list uids numerically
-p	for given comma-separated pids only (default all pids)
-t	terse (pid only) output

netstat

监听网络信息。

netstat
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        1      0 ::ffff:192.168.0.101:42 ::ffff:47.103.16.184:ht CLOSE_WAIT  
tcp        0      0 ::ffff:192.168.0.101:39 ::ffff:111.202.1.250:ht ESTABLISHED 
tcp        1      0 ::ffff:192.168.0.101:42 ::ffff:47.103.16.184:ht CLOSE_WAIT  
udp     8448      0 192.168.0.101:bootpc    192.168.0.1:bootps      ESTABLISHED 
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags       Type       State           I-Node Path
unix  2      [ ]         DGRAM                        1635 @suilst
unix  3      [ ]         DGRAM                       36778 @/data/system/xiaomi.miui.android.f6450b82f5-perfevents.perf-event-channel.sock
unix  2      [ ]         DGRAM                       15159 /dev/socket/qmux_radio/rild_sync_0
unix  2      [ ]         DGRAM                       15161 /dev/socket/qmux_radio/rild_sync_1
unix  2      [ ]         DGRAM                       33548 /data/misc/wifi/sockets/wpa_ctrl_716-1
......

ps

查看进程信息

ps
USER      PID   PPID  VSIZE  RSS   WCHAN              PC  NAME
root      1     0     16332  1616  SyS_epoll_ 00004c7cf8 S /init
root      2     0     0      0       kthreadd 0000000000 S kthreadd
root      3     2     0      0     smpboot_th 0000000000 S ksoftirqd/0
root      5     2     0      0     worker_thr 0000000000 S kworker/0:0H
root      6     2     0      0     diag_socke 0000000000 S kworker/u16:0
root      7     2     0      0     rcu_gp_kth 0000000000 S rcu_preempt
root      8     2     0      0     rcu_gp_kth 0000000000 S rcu_sched
root      9     2     0      0     rcu_gp_kth 0000000000 S rcu_bh
root      10    2     0      0     nocb_leade 0000000000 S rcuop/0
root      11    2     0      0     nocb_leade 0000000000 S rcuos/0
root      12    2     0      0     nocb_leade 0000000000 S rcuob/0
root      13    2     0      0     smpboot_th 0000000000 S migration/0
root      14    2     0      0     smpboot_th 0000000000 S migration/1
......

top

实时显示CPU消耗排名的进程信息。

top
User 1%, System 10%, IOW 0%, IRQ 0%
User 2 + Nice 0 + Sys 11 + Idle 93 + IOW 0 + IRQ 0 + SIRQ 0 = 106

  PID USER     PR  NI CPU% S  #THR     VSS     RSS PCY Name
 9877 root     20   0   9% R     1   9112K   1884K  fg top
 9848 root     20   0   0% S     1      0K      0K  fg kworker/u16:4
    3 root     20   0   0% S     1      0K      0K  fg ksoftirqd/0
    5 root      0 -20   0% S     1      0K      0K  fg kworker/0:0H
    6 root     20   0   0% S     1      0K      0K  fg kworker/u16:0
    7 root     20   0   0% S     1      0K      0K  fg rcu_preempt
    8 root     20   0   0% S     1      0K      0K  fg rcu_sched
    9 root     20   0   0% S     1      0K      0K  fg rcu_bh
   10 root     20   0   0% S     1      0K      0K  fg rcuop/0
   11 root     20   0   0% S     1      0K      0K  fg rcuos/0
   12 root     20   0   0% S     1      0K      0K  fg rcuob/0
   13 root     RT   0   0% S     1      0K      0K  fg migration/0

free

空闲内存信息

free
		total        used        free      shared     buffers
Mem:       2984718336  2234626048   750092288     2564096    14450688
-/+ buffers/cache:     2220175360   764542976
Swap:      1073737728   366358528   707379200

getprop

查看property属性信息。

getprop
[DEVICE_PROVISIONED]: [1]
[acdb_id_para_version]: [AL1512-Audiopara-V26-20180420]
[af.fast_track_multiplier]: [2]
[audio.deep_buffer.media]: [true]
[audio.dolby.ds2.enabled]: [true]
[audio.dolby.ds2.hardbypass]: [true]
[audio.offload.buffer.size.kb]: [64]
[audio.offload.disable]: [true]
[audio.offload.gapless.enabled]: [true]
[audio.offload.min.duration.secs]: [15]
[audio.offload.multiaac.enable]: [true]
[audio.offload.multiple.enabled]: [false]
[audio.offload.passthrough]: [false]
[audio.offload.pcm.16bit.enable]: [true]
[audio.offload.pcm.24bit.enable]: [true]
[audio.offload.track.enable]: [true]
[audio.offload.video]: [true]
[audio.parser.ip.buffer.size]: [0]
[audio.playback.mch.downsample]: [true]
[audio.pp.asphere.enabled]: [false]
[audio.safx.pbe.enabled]: [true]
[audio_hal.period_size]: [192]
[audio_para_version]: [AL1512-Audiopara-V26-20180420]
[av.debug.disable.pers.cache]: [1]
[bluetooth.hfp.client]: [1]
[camera.clientname]: [cameraserver]
[camera.display.lmax]: [1280x720]
[camera.display.umax]: [1920x1080]
[camera.hal1.packagelist]: [com.skype.raider,com.google.android.talk]
[camera.lowpower.record.enable]: [1]
[dalvik.vm.appimageformat]: [lz4]
[dalvik.vm.bg-dex2oat-threads]: [2]
[dalvik.vm.dex2oat-Xms]: [64m]
[dalvik.vm.dex2oat-Xmx]: [512m]
[dalvik.vm.dex2oat-threads]: [6]
[dalvik.vm.dexopt.secondary]: [true]
[dalvik.vm.heapgrowthlimit]: [192m]
[dalvik.vm.heapmaxfree]: [8m]
[dalvik.vm.heapminfree]: [4m]
[dalvik.vm.heapsize]: [512m]
......

高通日志命令

# modem回调接口压力测试
diag_callback_sample
diag_dci_sample
diag_klog
# modem log信息
diag_mdlog
diag_socket_log
diag_uart_log
subsystem_ramdump

2 日志目录

android系统中还有很多常用的日志目录。我们可以通过adb命令把这些日志信息提取出来。

2.1 系统日志

# 内核日志目录
/d
# ANR日志
/data/anr
# bootchart日志
/data/bootchart
# bugreport日志文件
/data/bugreports
/data/misc/bootchart
/data/misc/boottrace
/data/misc/profman
/data/misc/trace
/data/misc/zoneinfo
/data/system/dropbox
/data/system/heapdump
/data/system/netstats
/data/system/procstats
/data/system/usagestats
# 非通用,某些平台日志目录。
/data/system.log.*
/data/tombstones
# bugreport日志文件目录
/data/user_de/0/com.android.shell/files/bugreports
/sys/bootinfo
# 内核调试信息
/sys/kernel/debug

2.2 运行信息

很多系统的运行信息都会临时保存在/proc系统目录下。我们可以根据调试需要,查看相关信息。

ls -1
boot_status
buddyinfo
cgroups
cmdline
cpuinfo
crypto
device-tree
diskstats
filesystems
interrupts
iomem
ioports
irq
kallsyms
key-users
kmsg
kpagecount
kpageflags
loadavg
locks
meminfo
misc
modules
mounts
net
pagetypeinfo
partitions
schedstat
scsi
self
serial_num
softirqs
stat
swaps
sys
sysrq-trigger
thread-self
timer_list
timer_stats
tp_lockdown_info
tty
uid_cputime
uid_stat
uptime
version
vmallocinfo
vmstat
zoneinfo

2.3 cgroup信息

# 各控制组文件系统目录
mount |grep cgroup
none on /acct type cgroup (rw,relatime,cpuacct)
none on /dev/memcg type cgroup (rw,relatime,memory)
none on /dev/cpuctl type cgroup (rw,relatime,cpu)
none on /dev/cpuset type cgroup (rw,relatime,cpuset,noprefix,release_agent=/sbin/cpuset_release_agent)
none on /sys/fs/cgroup type tmpfs (rw,seclabel,relatime,size=1436904k,nr_inodes=359226,mode=750,gid=1000)
none on /sys/fs/cgroup/memory type cgroup (rw,relatime,memory)
none on /sys/fs/cgroup/freezer type cgroup (rw,relatime,freezer)

# 然后可以进入控制组目录查看相关控制组信息

3 平台日志

3.1 MediaTek

MTK平台的所有的日志都会收集在这个目录下:sdcard/mtklog
MTK还有自己的专用的日志工具来解析显示这些日志。比直接看日志文件更方便。

3.2 Qualcom

QUALCOM平台还有ramdump日志,通过QPST工具来提取。

热门相关:无量真仙   寂静王冠   豪门闪婚:帝少的神秘冷妻   战神   名门天后:重生国民千金