Android系统提供了logcat工具来记录打印log,先来聊一下logcat的使用
adb logcat --help
Usage: logcat [options] [filterspecs]
options include:
-s Set default filter to silent.
Like specifying filterspec '*:s'
-f <filename> Log to file. Default to stdout
-r [<kbytes>] Rotate log every kbytes. (16 if unspecified). Requires -f
-n <count> Sets max number of rotated logs to <count>, default 4
-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 default is -b main -b system.
-B output the log in binary
-C colored output
filterspecs are a series of
<tag>[:priority]
where <tag> is a log component tag (or * for all) 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>:v
If 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_LOG
or defaults to "brief"
比较常使用的命令有
adb logcat -f /sdcard/log.txt 将log输出到sdcard下的log.txt文件中
adb logcat -v time 输出log详细时间信息
adb logcat -v thread 输出log线程信息
adb logcat -t 50 输出最近50条log信息
adb logcat -c 清除日志缓冲区
adb logcat *:E 打印所有ERROR级别及更高级别的日志信息
adb logcat Test:I 打印所有INFO级别以及更高级别的TAG为Test的日志信息
linux系统和Mac系统下,logcat结合grep命令可以极大的提高效率
比如adb locat | grep Runtime可以过滤所有Runtime信息
windows系统下,建议结合强大的文本编辑器如notepad
在android代码中,我们通常这样调用:
Log.i(tagname, message);很多人,为了方便在IDE中清楚的查看log信息,使用error级别的log
Log.e(tagname, message);这其实是对log的一种误用,想要清楚的查看log信息,可以通过过滤tag,甚至是log本身的内容。通过提高log的级别来查看临时信息是很不科学的。这种代码放到线上容易被log误导,本来没有错误的,却打印了一堆ERROR级别的log,而且不方便追踪问题。
打印log的时候最好做一个开关,有些log调试的时候需要输出,但是发布的时候不需要输出。
Android系统本身提供了一个很好的开关
Log.isLoggable
boolean isDebug=Log.isLoggable(TagName, Log.VERBOSE); if (isDebug) { Log.w(TagName, "log"); }isDebug默认是false,当执行
adb shell setprop log.tag.TagName VERBOSE之后,isDebug会变为true
欢迎扫描二维码,关注公众号