-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalogview.go
412 lines (344 loc) · 8.6 KB
/
alogview.go
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"github.com/mattn/go-isatty"
)
// Custom type for multiple flags
type stringSetValue struct {
values map[string]bool
}
type color int
const (
black color = iota
red
green
yellow
blue
magenta
cyan
white
)
const reset = "\033[0m"
type logLine struct {
raw string
time string
pid int
tid int
level string
tag string
message string
}
// A filter implements the `filter()` method, which is expected to run as a goroutine.
type filter interface {
filter(chan<- *logLine, <-chan *logLine)
}
type packageFilter struct {
packages map[string]bool
pids map[int]bool
}
type tagFilter struct {
tags map[string]bool
}
var (
pslineMatcher *regexp.Regexp
loglineMatcher *regexp.Regexp
startprocMatcher *regexp.Regexp
diedprocMatcher *regexp.Regexp
killprocMatcher *regexp.Regexp
// global store for additional ADB options
adbcmd = "adb"
adbargs []string
)
func init() {
// The line pattern is "${user:w} ${pid:d} ${ppid:d} ${vsz:d} ${rss:d} ${wchan:w} ${addr:w} ${s:w} ${name:w}"
pslineMatcher = regexp.MustCompile(`\w+\s+(\d+)\s+\d+\s+\d+\s+\d+\s+\w+\s+\w+\s+[A-Z]\s+(.*)$`)
// The line pattern is "${datetime} ${pid} ${tid} ${level} ${tag}: ${message}"
// the datetime is in the format "MM-DD hh:mm:ss.sss"
// the tag is optional, at least sometimes missing
loglineMatcher = regexp.MustCompile(`(\d\d-\d\d \d\d:\d\d:\d\d.\d\d\d)\s+(\d+)\s+(\d+)\s+([DVIWEF])(.*?):\s+(.*)$`)
// The start proc pattern is "Start Proc ${pid}:${package1}/${user} for ((activity|broadcast|service) ${package2}/${component})?"
startprocMatcher = regexp.MustCompile(`Start proc (\d+):([A-Za-z0-9_.]+)/\w+`)
// The died proc pattern is "Process ${package} (pid ${pid}) has died: ${reason}"
diedprocMatcher = regexp.MustCompile(`Process ([A-Za-z0-9_.]+) \(pid (\d+)\) has died: .*$`)
// The stop proc pattern is "Killing ${pid}:${package}/${user} (adj ${unknown}): ${reason}"
killprocMatcher = regexp.MustCompile(`Killing (\d+):([A-Za-z0-9_.]+)/\w+ [^:]+: .*$`)
}
func main() {
d := flag.Bool("d", false, "use USB device (error if multiple devices connected)")
e := flag.Bool("e", false, "use TCP/IP device (error if multiple TCP/IP devices available)")
h := flag.Bool("h", false, "show this help message")
s := flag.String("s", "", "use device with given serial (overrides $ANDROID_SERIAL)")
tags := newStringSetValue()
flag.Var(tags, "t", "list of tags")
flag.Parse()
if *h {
usage()
}
if *d && *e {
fmt.Fprintln(os.Stderr, "invalid parameters: -e and -d must not be specified both")
usage()
}
if *d {
adbargs = append(adbargs, "-d")
}
if *e {
adbargs = append(adbargs, "-e")
}
if len(*s) > 0 {
adbargs = append(adbargs, "-s", *s)
}
adbenv, adbOverride := os.LookupEnv("ADB")
if adbOverride {
if len(adbenv) == 0 {
fatal("ADB environment variable must not be set to empty string")
}
adbcmd = adbenv
}
_, suppresscolor := os.LookupEnv("NO_COLOR")
suppresscolor = suppresscolor || !isatty.IsTerminal(os.Stdout.Fd())
filters := make([]filter, 0)
if len(tags.values) > 0 {
filters = append(filters, newTagFilter(tags.values))
}
if len(flag.Args()) > 0 {
filters = append(filters, newPackageFilter(os.Args))
}
rawlines := make(chan *logLine)
filtered := startFilters(filters, rawlines)
go func() {
if suppresscolor {
for {
line := <-filtered
fmt.Printf("%s\n", line.raw)
}
} else {
for {
line := <-filtered
fmt.Printf("%s%s%s\n", colorForLevel(line.level), line.raw, reset)
}
}
}()
r := startLogCollection()
parseLogs(r, rawlines)
}
func usage() {
fmt.Fprintf(os.Stderr, "usage:\t%s [-d|-e] [-s serial] [packagename]\n", os.Args[0])
flag.PrintDefaults()
os.Exit(1)
}
// Start all filter functions as goroutines, with channels set up between them to send log lines down the chain.
func startFilters(filters []filter, rawlines chan *logLine) <-chan *logLine {
linesout := rawlines
for _, f := range filters {
pipe := make(chan *logLine)
go f.filter(pipe, linesout)
linesout = pipe
}
return linesout
}
// Start an adb instance and return the reader end of the pipe.
func startLogCollection() io.Reader {
r, w := io.Pipe()
go runADB(w, "logcat")
return r
}
// Read log lines from the reader, parse them into a logLine struct and send them to the linesout chan.
func parseLogs(r io.Reader, linesout chan<- *logLine) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "--------- beginning of") {
continue
}
msg, err := parseLine(line)
if err != nil {
warn(err)
continue
}
linesout <- msg
}
}
// Return the color escape code for the log level.
func colorForLevel(level string) string {
s := ""
switch level {
case "V":
s = termfg(white)
case "D":
s = termfg(cyan)
case "I":
s = termfg(green)
case "W":
s = termfg(yellow)
case "E":
s = termfg(red)
case "F":
s = termfg(magenta)
}
return s
}
func termfg(fg color) string {
return fmt.Sprintf("\033[3%dm", fg)
}
func fatal(msg ...interface{}) {
warn(msg...)
os.Exit(1)
}
func warn(msg ...interface{}) {
fmt.Fprintln(os.Stderr, msg...)
}
func runADB(out io.WriteCloser, args ...string) {
args = append(adbargs, args...)
cmd := exec.Command(adbcmd, args...)
cmd.Stdout = out
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fatal(err)
}
if err := out.Close(); err != nil {
fatal(err)
}
}
func parseLine(line string) (*logLine, error) {
if parsed := loglineMatcher.FindStringSubmatch(line); parsed != nil {
pid, e1 := strconv.Atoi(parsed[2])
if e1 != nil {
return nil, e1
}
tid, e2 := strconv.Atoi(parsed[3])
if e2 != nil {
return nil, e2
}
return &logLine{
raw: line,
time: parsed[1],
pid: pid,
tid: tid,
level: parsed[4],
tag: strings.TrimSpace(parsed[5]),
message: parsed[6]}, nil
}
return nil, fmt.Errorf("failed to match log line \"%s\"", line)
}
// Create a new tagFilter from a list of tags.
func newTagFilter(tags map[string]bool) *tagFilter {
return &tagFilter{
tags: tags,
}
}
func (tf *tagFilter) filter(out chan<- *logLine, in <-chan *logLine) {
for {
line := <-in
if tf.tags[line.tag] {
out <- line
}
}
}
// Create a packageFilter from a list of package names.
func newPackageFilter(pkgnames []string) *packageFilter {
packages := make(map[string]bool)
for _, pkg := range pkgnames {
packages[pkg] = true
}
pids := getProcs(packages)
if len(pids) == 0 {
warn("no packages found matching the given package(s)")
}
return &packageFilter{
packages: packages,
pids: pids,
}
}
// Execute `adb shell ps` and parse the output to get a list of currently running processes; return the process IDs.
func getProcs(packages map[string]bool) map[int]bool {
r, w := io.Pipe()
go runADB(w, "shell", "ps")
scanner := bufio.NewScanner(r)
pids := make(map[int]bool)
for scanner.Scan() {
parsed := pslineMatcher.FindStringSubmatch(scanner.Text())
if parsed != nil {
pid := atoi(parsed[1])
pkg := parsed[2]
if packages[pkg] {
pids[pid] = true
}
}
}
if err := scanner.Err(); err != nil {
fatal(err)
}
return pids
}
func atoi(str string) int {
i, err := strconv.Atoi(str)
if err != nil {
panic(err)
}
return i
}
func (pf *packageFilter) filter(out chan<- *logLine, in <-chan *logLine) {
for {
line := <-in
if line.tag == "ActivityManager" && line.level == "I" {
// start proc
if parsedmsg := startprocMatcher.FindStringSubmatch(line.message); parsedmsg != nil {
pid := atoi(parsedmsg[1])
pkg := parsedmsg[2]
if pf.packages[pkg] {
pf.pids[pid] = true
out <- line
continue
}
}
// proc died
if parsedmsg := diedprocMatcher.FindStringSubmatch(line.message); parsedmsg != nil {
pkg := parsedmsg[1]
pid := atoi(parsedmsg[2])
if pf.packages[pkg] || pf.pids[pid] {
delete(pf.pids, pid)
out <- line
continue
}
}
// proc killed
if parsedmsg := killprocMatcher.FindStringSubmatch(line.message); parsedmsg != nil {
pid := atoi(parsedmsg[1])
pkg := parsedmsg[2]
if pf.packages[pkg] || pf.pids[pid] {
delete(pf.pids, pid)
out <- line
}
}
} else if pf.pids[line.pid] {
out <- line
}
}
}
func newStringSetValue() *stringSetValue {
return &stringSetValue{
values: make(map[string]bool),
}
}
func (p *stringSetValue) String() string {
accu := ""
for k := range p.values {
accu += k + ", "
}
return strings.TrimRight(accu, ", ")
}
func (p *stringSetValue) Set(value string) error {
p.values[value] = true
return nil
}
func (p *stringSetValue) Get() interface{} {
return p.values
}