extracting-logs-with-logcat

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Extracting Logs With logcat — Reading Device Logs

使用 logcat 提取日志——读取设备日志

This skill covers
adb logcat
end-to-end: streaming vs dumping, buffer selection, filter expressions, format flags, PID and time filters, file rotation, and the R8 rule that strips
Log.d
from release builds. The companion CI capture-on-failure pattern lives in
../../automation/scripting-adb-for-ci/SKILL.md
.
此 skill 全面介绍
adb logcat
:包括流式读取与转储、缓冲区选择、过滤表达式、格式标志、PID 与时间过滤器、文件轮转,以及从发布构建中移除
Log.d
的 R8 规则。配套的 CI 失败时采集模式位于
../../automation/scripting-adb-for-ci/SKILL.md
。

When to use this skill

何时使用此 skill

  • A test fails on CI; the developer needs to dump the device log into the artefact archive.
  • The developer's
    adb logcat | grep MyApp
    is overwhelming the SSH session — the logcat-side filter is the fix.
  • A scenario only reproduces inside
    system_server
    or
    crash
    buffers, not the default
    main
    .
  • The developer wants structured logs (
    -v json
    ) for machine ingestion.
  • A
    Log.d("Sensitive", "...")
    call appears to leak in release — the R8
    -assumenosideeffects
    rule is missing.
  • Logs disappear after the app is killed by Doze/ANR —
    --pid
    plus a re-resolution loop is needed.
  • CI 中测试失败;开发者需要将设备日志转储到制品归档中。
  • 开发者的
    adb logcat | grep MyApp
    淹没了 SSH 会话——解决方案是在 logcat 端进行过滤。
  • 某个场景只能在
    system_server
    或
    crash
    缓冲区中复现,而不能在默认的
    main
    缓冲区中复现。
  • 开发者需要结构化日志(
    -v json
    )以供机器摄取。
  • 发布版本中出现了可能泄漏敏感信息的
    Log.d("Sensitive", "...")
    调用——说明缺少 R8
    -assumenosideeffects
    规则。
  • 应用被 Doze/ANR 终止后日志消失——需要使用
    --pid
    配合重新解析 PID 的循环。

When NOT to use this skill

何时不应使用此 skill

  • Capturing a screenshot or video. Use
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    .
  • Pulling a generic file from the device. Use
    ../../transfer/extracting-test-artifacts/SKILL.md
    .
  • The whole script — retries, port forwarding, parallel device fan-out. Use
    ../../automation/scripting-adb-for-ci/SKILL.md
    .
  • Driving gestures or settings changes. Use
    ../../control/injecting-input-and-state/SKILL.md
    .
  • 截取屏幕截图或视频。请使用
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    。
  • 从设备中提取通用文件。请使用
    ../../transfer/extracting-test-artifacts/SKILL.md
    。
  • 编写完整脚本——包括重试、端口转发和并行设备分发。请使用
    ../../automation/scripting-adb-for-ci/SKILL.md
    。
  • 执行手势或更改设置。请使用
    ../../control/injecting-input-and-state/SKILL.md
    。

Prerequisites

前置条件

  • adb get-state
    returns
    device
    . See
    ../../devices/connecting-to-devices/SKILL.md
    .
  • For
    -v json
    : device API 30+ (Android 11+). Stack with
    -v UTC -v year
    for unambiguous timestamps.
  • For per-PID filtering:
    adb shell pidof -s <pkg>
    requires API 24+ (toybox
    pidof -s
    ); on older releases use
    adb shell ps -A | grep <pkg>
    .
  • adb get-state
    返回
    device
    。请参阅
    ../../devices/connecting-to-devices/SKILL.md
    。
  • 对于
    -v json
    :设备 API 30+(Android 11+)。可结合
    -v UTC -v year
    使用,以获得无歧义的时间戳。
  • 对于按 PID 过滤:
    adb shell pidof -s <pkg>
    需要 API 24+(toybox
    pidof -s
    );在较旧版本上请使用
    adb shell ps -A | grep <pkg>
    。

Three fundamental operations

三种基本操作

CommandBehavior
adb logcat
Stream the device log to stdout; runs until interrupted.
adb logcat -d
"Dumps the log and exits." Snapshot mode — perfect for CI.
adb logcat -c
"Clears the log buffer." Run this before reproducing a bug.
(Verbatim quotes from developer.android.com/tools/logcat.)
Idiomatic CI capture pattern:
bash
adb logcat -c                           # clear before scenario
./run-scenario.sh                       # reproduce
adb logcat -d > artifacts/log.txt       # dump after
命令行为
adb logcat
将设备日志流式输出到 stdout;一直运行直到被中断。
adb logcat -d
“转储日志并退出。”快照模式——非常适合 CI。
adb logcat -c
“清空日志缓冲区。”在复现 bug 前运行此命令。
(引自 developer.android.com/tools/logcat。)
惯用的 CI 采集模式:
bash
adb logcat -c                           # clear before scenario
./run-scenario.sh                       # reproduce
adb logcat -d > artifacts/log.txt       # dump after

Buffer selection

缓冲区选择

-b <name>
selects which kernel/userspace ring buffer is read. Buffers (developer.android.com/tools/logcat):
BufferWhat it contains
main
Default app-side buffer. Does NOT contain system/crash.
system
Framework / system_server messages.
crash
Tombstones + unhandled-exception output.
events
Structured/binary system event buffer. Pair with
-v descriptive
to decode tag names.
radio
Radio/telephony related messages.
kernel
Kernel buffer.
all
Every buffer.
default
Implicit set:
main
,
system
,
crash
.
Multiple
-b
flags or comma-separated lists both work:
bash
adb logcat -b radio
adb logcat -b main -b radio -b events
adb logcat -b main,radio,events
The
events
buffer is where to look for
am_*
,
wm_*
,
input_focus
,
notification_*
— emitted by the framework for instrumentation, not for human reading. Decode tag names with:
bash
adb logcat -b events -v descriptive
-b <name>
用于选择要读取的 kernel/userspace 环形缓冲区。缓冲区列表(developer.android.com/tools/logcat):
缓冲区内容
main
默认的应用侧缓冲区。不包含 system/crash。
system
Framework / system_server 消息。
crash
Tombstones 和未处理异常输出。
events
结构化/二进制系统事件缓冲区。配合
-v descriptive
使用可解码标签名称。
radio
无线电/电话相关消息。
kernel
Kernel 缓冲区。
all
所有缓冲区。
default
隐式集合:
main
、
system
、
crash
。
可以使用多个
-b
标志,也可以使用逗号分隔的列表:
bash
adb logcat -b radio
adb logcat -b main -b radio -b events
adb logcat -b main,radio,events
events
缓冲区包含
am_*
、
wm_*
、
input_focus
、
notification_*
等由 framework 为 instrumentation 发出、并非供人直接阅读的事件。可使用以下命令解码标签名称:
bash
adb logcat -b events -v descriptive

Priority ladder + filter expressions

优先级阶梯与过滤表达式

Filter specs are space-separated
tag:priority
pairs.
*
matches every tag.
LetterMeaning
V
Verbose
D
Debug
I
Info
W
Warning
E
Error
F
Fatal
S
"Silent (highest priority, nothing is printed)"
Setting
*:S
silences everything, then any preceding
tag:P
re-enables that tag at priority
P
or above. The canonical "show only my app's logs" idiom:
bash
adb logcat ActivityManager:I MyApp:D *:S
"Suppress all logs except ActivityManager (Info+) and MyApp (Debug+)" — developer.android.com/tools/logcat.
Other staples:
bash
adb logcat *:W                          # warnings and above, all tags
adb logcat *:E                          # errors and above (very common in CI)
zsh/bash will glob-expand
*:S
outside of quotes when there is a file named
S
in cwd — quote when scripting:
bash
adb logcat "ActivityManager:I MyApp:D *:S"
The same filter can be the host default via env var:
bash
export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"
过滤规格由空格分隔的
tag:priority
对组成。
*
匹配所有标签。
字母含义
V
Verbose
D
Debug
I
Info
W
Warning
E
Error
F
Fatal
S
“Silent(最高优先级,不打印任何内容)”
设置
*:S
会静默所有内容,随后任意位于其前的
tag:P
都会重新启用对应标签,并显示优先级
P
及以上的日志。显示“我的应用日志”的标准写法:
bash
adb logcat ActivityManager:I MyApp:D *:S
“抑制除 ActivityManager(Info+)和 MyApp(Debug+)之外的所有日志”——developer.android.com/tools/logcat。
其他常用用法:
bash
adb logcat *:W                          # warnings and above, all tags
adb logcat *:E                          # errors and above (very common in CI)
在 zsh/bash 中,如果当前目录存在名为
S
的文件,未加引号的
*:S
会被 glob 展开;编写脚本时应加引号:
bash
adb logcat "ActivityManager:I MyApp:D *:S"
也可以通过环境变量将同一个过滤器设置为主机端默认值:
bash
export ANDROID_LOG_TAGS="ActivityManager:I MyApp:D *:S"

Format flags —
-v <format>

格式标志——
-v <format>

FormatWhat you get
brief
"Displays priority, tag, and PID"
long
"All metadata fields with blank lines between messages"
process
"PID only"
raw
"Raw log message with no metadata"
tag
"Priority and tag only"
thread
"Legacy format showing priority, PID, and TID"
threadtime
DEFAULT. "Date, time, priority, tag, PID, and TID"
time
"Date, time, priority, tag, and PID"
Format modifiers stack with
-v
(comma-combinable or repeatable):
ModifierEffect
color
Per-priority colour.
descriptive
Decode event log tag names.
epoch
Time in seconds since 1970-01-01.
monotonic
CPU seconds from last boot.
printable
Escape binary content.
uid
UID or Android ID of logged process.
usec
Time with microsecond precision.
UTC
Time as UTC.
year
Add year to displayed time.
zone
Add local time zone.
bash
adb logcat -v json -v UTC -v year       # Android 11+; structured stream, unambiguous time
adb logcat -b all -v color -d           # color dump, all buffers
Default-line example (developer.android.com/tools/logcat):
I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action.MAIN ... }
Schema for
brief
:
<priority>/<tag>(<PID>): <message>
.
threadtime
adds date/time/TID.
格式输出内容
brief
“显示优先级、标签和 PID”
long
“显示所有元数据字段,并在消息之间留空行”
process
“仅 PID”
raw
“原始日志消息,不含元数据”
tag
“仅优先级和标签”
thread
“旧版格式,显示优先级、PID 和 TID”
threadtime
默认值。“日期、时间、优先级、标签、PID 和 TID”
time
“日期、时间、优先级、标签和 PID”
格式修饰符可与
-v
叠加使用(可通过逗号组合或重复指定):
修饰符效果
color
按优先级着色。
descriptive
解码事件日志标签名称。
epoch
距离 1970-01-01 的秒数。
monotonic
自上次启动以来的 CPU 秒数。
printable
转义二进制内容。
uid
记录进程的 UID 或 Android ID。
usec
精确到微秒的时间。
UTC
UTC 时间。
year
在显示时间中加入年份。
zone
加入本地时区。
bash
adb logcat -v json -v UTC -v year       # Android 11+; structured stream, unambiguous time
adb logcat -b all -v color -d           # color dump, all buffers
默认行示例(developer.android.com/tools/logcat):
I/ActivityManager(  585): Starting activity: Intent { action=android.intent.action.MAIN ... }
brief
的格式模式为:
<priority>/<tag>(<PID>): <message>
。
threadtime
还会添加日期/时间和 TID。

Time and PID filters

时间与 PID 过滤器

  • -T '<date> <time>'
    — start at the first entry on or after the given timestamp. Format matches
    threadtime
    , e.g.
    '01-01 12:00:00.000'
    .
  • -T <count>
    — print the last N entries from the buffer, then continue streaming.
  • -t <count>
    — print the last N entries, then exit (i.e.
    -t
    is
    -T
    with auto-quit).
  • --pid <pid>
    — emit only entries from a single process. Combine with
    pidof
    :
bash
adb logcat --pid=$(adb shell pidof -s com.example.app)
pidof -s
returns a single pid; without
-s
you get a space-separated list which
--pid
will not accept directly. Wrap a re-resolution loop if the app may be killed and restarted (Doze, ANR, crash):
bash
while true; do
  PID=$(adb shell pidof -s com.example.app 2>/dev/null)
  [ -n "$PID" ] && adb logcat --pid="$PID"
  sleep 1
done
  • -T '<date> <time>'
    ——从给定时间戳或之后的第一个条目开始输出。格式与
    threadtime
    匹配,例如
    '01-01 12:00:00.000'
    。
  • -T <count>
    ——打印缓冲区中的最后 N 个条目,然后继续流式输出。
  • -t <count>
    ——打印最后 N 个条目,然后退出(即
    -t
    是带自动退出功能的
    -T
    )。
  • --pid <pid>
    ——仅输出单个进程的条目。可结合
    pidof
    使用:
bash
adb logcat --pid=$(adb shell pidof -s com.example.app)
pidof -s
返回单个 PID;不使用
-s
时会返回以空格分隔的 PID 列表,而
--pid
无法直接接受该列表。如果应用可能因 Doze、ANR 或 crash 被终止并重启,请包装一个重新解析 PID 的循环:
bash
while true; do
  PID=$(adb shell pidof -s com.example.app 2>/dev/null)
  [ -n "$PID" ] && adb logcat --pid="$PID"
  sleep 1
done

Buffer rotation and persistence

缓冲区轮转与持久化

For long captures, persist to a file with rotation:
FlagMeaning
-f <file>
Write to
<file>
instead of stdout. Subtle: with
adb logcat -f
, the file is host-side; with
adb shell logcat -f
, the path is device-side.
-r <kbytes>
Rotate output every N kilobytes. Requires
-f
.
-n <count>
Keep at most
<count>
rotated files (
logfile
,
logfile.1
, ...).
-G <size>
Resize the kernel log buffer for the selected
-b
ring (e.g.
1M
,
16M
). Persists for the life of
logd
.
-g
Print buffer sizes and current usages, then exit. Cheap diagnostics for "why am I missing logs?".
bash
adb logcat -G 16M                                     # grow the main buffer
adb logcat -g                                         # inspect sizes
adb logcat -b main -f /data/local/tmp/app.log \
           -r 1024 -n 8                               # 8x ~1MB rotated files (device-side)
adb shell logcat -b main -f /data/local/tmp/app.log \
           -r 1024 -n 8                               # same, but the device runs it
The
-G
resize is global to that buffer and persists across
logd
restarts (until reboot). Don't set 16 MB on a memory-constrained device and forget — release memory back with
-G 256K
after the suite if your CI farm is shared.
对于长时间采集,可通过轮转将日志持久化到文件:
标志含义
-f <file>
写入
<file>
而不是 stdout。**需要注意:**使用
adb logcat -f
时,文件位于主机端;使用
adb shell logcat -f
时,路径位于设备端。
-r <kbytes>
每 N KB 轮转一次输出。需要与
-f
一起使用。
-n <count>
最多保留
<count>
个轮转文件(
logfile
、
logfile.1
等)。
-G <size>
调整所选
-b
环形缓冲区的 kernel 日志缓冲区大小(例如
1M
、
16M
)。在
logd
生命周期内持续有效。
-g
打印缓冲区大小和当前使用量,然后退出。适合低成本诊断“为什么缺少日志?”等问题。
bash
adb logcat -G 16M                                     # grow the main buffer
adb logcat -g                                         # inspect sizes
adb logcat -b main -f /data/local/tmp/app.log \
           -r 1024 -n 8                               # 8x ~1MB rotated files (device-side)
adb shell logcat -b main -f /data/local/tmp/app.log \
           -r 1024 -n 8                               # same, but the device runs it
-G
的调整会全局应用于该缓冲区,并跨
logd
重启持续有效,直至设备重启。如果在内存受限的设备上设置 16 MB 后忘记恢复,应在测试套件结束后使用
-G 256K
归还内存,尤其是在共享 CI 设备集群中。

Stripping
Log.d
in release — R8 rule

在发布版本中移除
Log.d
——R8 规则

android.util.Log
calls remain in release APKs unless code-shrinking removes them. The standard idiom in
proguard-rules.pro
(R8/ProGuard):
pro
-assumenosideeffects class android.util.Log {
    public static *** v(...);
    public static *** d(...);
    public static *** i(...);
    public static boolean isLoggable(java.lang.String, int);
}
-assumenosideeffects
lets R8 treat the listed methods as pure no-ops, so all calls (and their string-builder argument expressions, when constants) are eliminated. Keep
w
,
e
,
wtf
for production diagnostics. With Timber: strip the
BuildConfig.DEBUG
-gated
DebugTree
plant and rely on a
ReleaseTree
that forwards to Crashlytics for warnings/errors.
For Compose specifically, do not
-assumenosideeffects
kotlin.jvm.internal.Intrinsics
— it removes null-checks the compiler relies on.
除非代码裁剪将其移除,否则
android.util.Log
调用会保留在发布 APK 中。
proguard-rules.pro
中的标准写法(R8/ProGuard):
pro
-assumenosideeffects class android.util.Log {
    public static *** v(...);
    public static *** d(...);
    public static *** i(...);
    public static boolean isLoggable(java.lang.String, int);
}
-assumenosideeffects
使 R8 将列出的方法视为纯粹的无操作,因此所有调用及其字符串构建器参数表达式在值为常量时都会被消除。生产诊断中应保留
w
、
e
、
wtf
。使用 Timber 时,应移除受
BuildConfig.DEBUG
控制的
DebugTree
plant,并依赖将警告和错误转发到 Crashlytics 的
ReleaseTree
。
对于 Compose specifically,不要对
kotlin.jvm.internal.Intrinsics
使用
-assumenosideeffects
——这会移除编译器所依赖的空值检查。

Patterns

模式

Pattern: WRONG —
adb logcat | grep MyApp
for filtering

模式:错误——使用
adb logcat | grep MyApp
进行过滤

bash
undefined
bash
undefined

WRONG

WRONG

adb logcat | grep MyApp
adb logcat | grep MyApp

WRONG because: the device sends every log line over the USB/TCP transport, then the host

WRONG because: the device sends every log line over the USB/TCP transport, then the host

discards 99% via grep. On a busy device this saturates the transport and the grep can lag

discards 99% via grep. On a busy device this saturates the transport and the grep can lag

behind real time. Worse,
grep
runs without -F, so a tag that contains regex metacharacters

behind real time. Worse,
grep
runs without -F, so a tag that contains regex metacharacters

(
.
,
(
,
+
) silently mismatches.

(
.
,
(
,
+
) silently mismatches.


```bash

```bash

RIGHT — filter at the logcat level

RIGHT — filter at the logcat level

adb logcat MyApp:D *:S

The device only emits matching lines; the transport is uncongested.
adb logcat MyApp:D *:S

设备只会输出匹配的行,因此传输通道不会拥塞。

Pattern: WRONG — assuming
-T <count>
exits

模式:错误——误以为
-T <count>
会退出

bash
undefined
bash
undefined

WRONG

WRONG

adb logcat -T 100 > tail.txt
adb logcat -T 100 > tail.txt

Hangs forever — -T <count> prints the last 100 lines THEN CONTINUES STREAMING.

Hangs forever — -T <count> prints the last 100 lines THEN CONTINUES STREAMING.


```bash

```bash

RIGHT —
-t
is
-T
with auto-exit

RIGHT —
-t
is
-T
with auto-exit

adb logcat -t 100 > tail.txt
undefined
adb logcat -t 100 > tail.txt
undefined

Pattern: structured logs for machine ingestion

模式:用于机器摄取的结构化日志

bash
adb logcat -v json -v UTC -v year -d -b all > run.jsonl
Each line is a single JSON object — pipe through
jq
:
bash
jq -c 'select(.priority == "ERROR")' run.jsonl
(
-v json
requires Android 11+ on the device.)
bash
adb logcat -v json -v UTC -v year -d -b all > run.jsonl
每一行都是一个独立的 JSON 对象——可通过
jq
进行管道处理:
bash
jq -c 'select(.priority == "ERROR")' run.jsonl
(
-v json
要求设备运行 Android 11+。)

Pattern: capture-on-failure — clear, run, dump

模式:失败时采集——清空、运行、转储

bash
adb logcat -c
./run-scenario.sh
RC=$?
if [ "$RC" -ne 0 ]; then
  adb logcat -d -v threadtime               > artifacts/logcat.txt
  adb logcat -d -b crash    -v threadtime   > artifacts/crash.txt
  adb logcat -d -b events   -v descriptive  > artifacts/events.txt
fi
exit "$RC"
-c
clears before the run so the dump captures only the scenario's logs.
bash
adb logcat -c
./run-scenario.sh
RC=$?
if [ "$RC" -ne 0 ]; then
  adb logcat -d -v threadtime               > artifacts/logcat.txt
  adb logcat -d -b crash    -v threadtime   > artifacts/crash.txt
  adb logcat -d -b events   -v descriptive  > artifacts/events.txt
fi
exit "$RC"
-c
会在运行前清空日志,因此转储内容仅包含当前场景产生的日志。

Pattern: PID-bound stream that survives a process restart

模式:可承受进程重启的 PID 绑定流

bash
while true; do
  PID=$(adb shell pidof -s com.example.app 2>/dev/null)
  if [ -n "$PID" ]; then
    adb logcat --pid="$PID" -v threadtime
  fi
  sleep 1
done
The outer loop re-resolves the PID after Doze/ANR/crash kills and restarts the app.
bash
while true; do
  PID=$(adb shell pidof -s com.example.app 2>/dev/null)
  if [ -n "$PID" ]; then
    adb logcat --pid="$PID" -v threadtime
  fi
  sleep 1
done
外层循环会在 Doze/ANR/crash 终止并重启应用后重新解析 PID。

Pattern:
-f
host vs device side

模式:
-f
的主机端与设备端差异

bash
undefined
bash
undefined

host-side rotation (file lives on the developer machine)

host-side rotation (file lives on the developer machine)

adb logcat -b main -f ~/logs/app.log -r 1024 -n 8
adb logcat -b main -f ~/logs/app.log -r 1024 -n 8

device-side rotation (file lives in /data/local/tmp on the device)

device-side rotation (file lives in /data/local/tmp on the device)

adb shell logcat -b main -f /data/local/tmp/app.log -r 1024 -n 8 adb pull /data/local/tmp/app.log ~/logs/app.log # later
undefined
adb shell logcat -b main -f /data/local/tmp/app.log -r 1024 -n 8 adb pull /data/local/tmp/app.log ~/logs/app.log # later
undefined

Mandatory rules

强制规则

  • MUST filter at the logcat level (e.g.
    MyApp:D *:S
    ), not via host-side
    grep
    . Filtering on the device avoids saturating the transport.
  • MUST quote filter strings containing
    *
    in zsh/bash (e.g.
    "MyApp:D *:S"
    ) — globbing eats the asterisk if a file named
    S
    exists in cwd.
  • MUST use
    -t <count>
    for "tail and exit".
    -T <count>
    continues streaming after the initial dump.
  • MUST use
    -d
    for snapshot dumps in CI. Streaming
    adb logcat
    requires explicit termination.
  • MUST call
    adb logcat -c
    before reproducing a bug whose log dump you want to attach. Otherwise the dump includes irrelevant prior history.
  • MUST distinguish
    adb logcat -f <file>
    (host-side path) from
    adb shell logcat -f <file>
    (device-side path). The shell forms diverge.
  • MUST add the R8
    -assumenosideeffects
    rule for
    android.util.Log
    v
    /
    d
    /
    i
    (and
    isLoggable
    ) when shipping release APKs that previously called
    Log.d
    with sensitive data. Keep
    w
    /
    e
    /
    wtf
    .
  • MUST NOT
    -assumenosideeffects
    kotlin.jvm.internal.Intrinsics
    — that removes null-check semantics the Kotlin compiler relies on.
  • MUST NOT rely on
    -v json
    on devices below Android 11 — silently emits an empty stream.
  • PREFERRED: stack
    -v threadtime,year,UTC
    (or
    -v threadtime -v year -v UTC
    ) for unambiguous absolute timestamps in CI artefacts.
  • PREFERRED: run with
    -G 16M
    for the
    main
    buffer when capturing slow-burning bugs, and reset to default in teardown.
  • 必须在 logcat 层进行过滤(例如
    MyApp:D *:S
    ),而不是使用主机端的
    grep
    。在设备端过滤可避免传输通道饱和。
  • 必须在 zsh/bash 中为包含
    *
    的过滤字符串加引号(例如
    "MyApp:D *:S"
    )——如果当前目录存在名为
    S
    的文件,glob 会吞掉星号。
  • 必须使用
    -t <count>
    实现“输出尾部内容后退出”。
    -T <count>
    会在初始转储后继续流式输出。
  • 必须在 CI 中使用
    -d
    执行快照转储。流式的
    adb logcat
    需要显式终止。
  • 必须在复现需要附加日志转储的 bug 前调用
    adb logcat -c
    。否则转储中会包含无关的历史日志。
  • 必须区分
    adb logcat -f <file>
    (主机端路径)与
    adb shell logcat -f <file>
    (设备端路径)。这两种 shell 形式存在差异。
  • 必须为此前使用
    Log.d
    处理敏感数据的发布 APK 添加 R8
    -assumenosideeffects
    规则,以移除
    android.util.Log
    的
    v
    /
    d
    /
    i
    (以及
    isLoggable
    )。保留
    w
    /
    e
    /
    wtf
    。
  • 禁止对
    kotlin.jvm.internal.Intrinsics
    使用
    -assumenosideeffects
    ——这会移除 Kotlin 编译器依赖的空值检查语义。
  • 禁止依赖 Android 11 以下设备上的
    -v json
    ——它会静默输出空流。
  • **推荐:**叠加使用
    -v threadtime,year,UTC
    (或
    -v threadtime -v year -v UTC
    ),为 CI 制品提供无歧义的绝对时间戳。
  • **推荐:**采集缓慢出现的 bug 时,对
    main
    缓冲区使用
    -G 16M
    ,并在清理阶段恢复默认值。

Verification

验证

  • No script in
    scripts/
    or
    .github/workflows/
    pipes
    adb logcat
    directly into
    grep
    for filtering. All filters are passed as logcat args.
  • CI capture-on-failure dumps include at least
    main
    ,
    crash
    , and
    events
    buffers.
  • Release APKs do not emit
    Log.d
    calls (verify via
    apkanalyzer dex packages app-release.apk | grep 'android.util.Log'
    returning only
    e
    /
    w
    /
    wtf
    ).
  • Filter strings containing
    *:S
    in shell scripts are quoted.
  • All
    --pid
    invocations use
    pidof -s <pkg>
    (singular) and re-resolve in a loop if the app may restart.
  • Every long-running
    adb logcat
    session in CI has a wall-clock budget (
    timeout 600s adb logcat ...
    ) so a stuck session doesn't fill the disk.
  • scripts/
    或
    .github/workflows/
    中没有脚本将
    adb logcat
    直接管道传给
    grep
    进行过滤。所有过滤器都应作为 logcat 参数传入。
  • CI 失败时采集的转储至少包含
    main
    、
    crash
    和
    events
    缓冲区。
  • 发布 APK 不输出
    Log.d
    调用(可通过
    apkanalyzer dex packages app-release.apk | grep 'android.util.Log'
    进行验证,结果应仅包含
    e
    /
    w
    /
    wtf
    )。
  • Shell 脚本中包含
    *:S
    的过滤字符串均已加引号。
  • 所有
    --pid
    调用均使用
    pidof -s <pkg>
    (单数),并在应用可能重启时通过循环重新解析。
  • CI 中每个长时间运行的
    adb logcat
    会话都设有挂钟时间预算(
    timeout 600s adb logcat ...
    ),避免卡住的会话占满磁盘。

References

参考资料

  • developer.android.com/tools/logcat — buffer table, priority ladder, filter expressions,
    -v threadtime
    /
    json
    /
    descriptive
    , format modifiers,
    -T
    /
    -t
    /
    --pid
    /
    -r
    /
    -n
    /
    -G
    /
    -g
    flags, line-format schema.
  • developer.android.com/tools/adb —
    adb logcat
    host-side shorthand vs
    adb shell logcat
    .
  • developer.android.com/studio/build/shrink-code — R8
    -assumenosideeffects
    and the
    android.util.Log
    strip rule.
  • developer.android.com/reference/android/util/Log —
    Log.v
    /
    d
    /
    i
    /
    w
    /
    e
    /
    wtf
    /
    isLoggable
    signatures.
  • Research note
    tasks/research/A3-adb-observability-automation.md
    — full logcat surface,
    -f
    host-vs-device subtlety, R8 keep-rule rationale, capture-on-failure CI pattern.
  • Sibling skill:
    ../../architecture/understanding-adb-architecture/SKILL.md
    — server / daemon, transport.
  • Sibling skill:
    ../../devices/connecting-to-devices/SKILL.md
    — device states,
    wait-for-device
    .
  • Sibling skill:
    ../../devices/connecting-over-wifi/SKILL.md
    —
    adb pair
    /
    adb connect
    .
  • Sibling skill:
    ../../apps/installing-and-managing-apps/SKILL.md
    — installing the APK whose logs are being captured.
  • Sibling skill:
    ../../tests/running-instrumented-tests-via-adb/SKILL.md
    —
    am instrument -w -r
    interplay with logcat.
  • Sibling skill:
    ../../control/injecting-input-and-state/SKILL.md
    — driving gestures whose effects show up in logcat.
  • Sibling skill:
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    — companion screenshot capture.
  • Sibling skill:
    ../../transfer/extracting-test-artifacts/SKILL.md
    — pulling rotated log files from the device.
  • Sibling skill:
    ../../automation/scripting-adb-for-ci/SKILL.md
    — full CI capture-on-failure / retry / cleanup patterns.
  • Cross-set:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    — instrumentation logs interleaved with logcat.
  • Cross-set:
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    — Activity lifecycle events surfaced in
    events
    buffer.
  • Cross-set:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    — when log capture is the appropriate observability layer.
  • developer.android.com/tools/logcat——缓冲区表、优先级阶梯、过滤表达式、
    -v threadtime
    /
    json
    /
    descriptive
    、格式修饰符、
    -T
    /
    -t
    /
    --pid
    /
    -r
    /
    -n
    /
    -G
    /
    -g
    标志以及行格式模式。
  • developer.android.com/tools/adb——
    adb logcat
    主机端简写与
    adb shell logcat
    的区别。
  • developer.android.com/studio/build/shrink-code——R8
    -assumenosideeffects
    与
    android.util.Log
    移除规则。
  • developer.android.com/reference/android/util/Log——
    Log.v
    /
    d
    /
    i
    /
    w
    /
    e
    /
    wtf
    /
    isLoggable
    方法签名。
  • 研究笔记
    tasks/research/A3-adb-observability-automation.md
    ——完整的 logcat 功能面、
    -f
    主机端与设备端的细微差异、R8 keep-rule 原理以及 CI 失败时采集模式。
  • 关联 skill:
    ../../architecture/understanding-adb-architecture/SKILL.md
    ——server / daemon 与传输机制。
  • 关联 skill:
    ../../devices/connecting-to-devices/SKILL.md
    ——设备状态与
    wait-for-device
    。
  • 关联 skill:
    ../../devices/connecting-over-wifi/SKILL.md
    ——
    adb pair
    /
    adb connect
    。
  • 关联 skill:
    ../../apps/installing-and-managing-apps/SKILL.md
    ——安装待采集日志的 APK。
  • 关联 skill:
    ../../tests/running-instrumented-tests-via-adb/SKILL.md
    ——
    am instrument -w -r
    与 logcat 的交互。
  • 关联 skill:
    ../../control/injecting-input-and-state/SKILL.md
    ——执行会在 logcat 中体现结果的手势。
  • 关联 skill:
    ../../capture/capturing-screenshots-and-screenrecord/SKILL.md
    ——配套的截图采集。
  • 关联 skill:
    ../../transfer/extracting-test-artifacts/SKILL.md
    ——提取轮转后的日志文件。
  • 关联 skill:
    ../../automation/scripting-adb-for-ci/SKILL.md
    ——完整的 CI 失败时采集、重试与清理模式。
  • 跨集合:
    ../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
    ——与 logcat 交织的 instrumentation 日志。
  • 跨集合:
    ../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md
    ——在
    events
    缓冲区中呈现的 Activity 生命周期事件。
  • 跨集合:
    ../../../fundamentals/strategies/applying-testing-strategies/SKILL.md
    ——何时日志采集是合适的可观测性层。