forked from cloudfoundry/gorouter
/
prettifier.go
121 lines (99 loc) · 2.22 KB
/
prettifier.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
package main
import (
"bufio"
"flag"
"fmt"
"github.com/cloudfoundry/gosteno"
"io"
"os"
"strings"
)
var prettifier *gosteno.JsonPrettifier
var ignoreParseError = false
var helptext = `Usage: gosteno-prettify [OPTS] [FILE(s)]
Parses json formatted log lines from FILE(s), or stdin,
and displays a more human friendly version of each line to stdout.
Examples :
gosteno-prettify f - g
Prettify f's contents, then standard input, then g's contents.
gosteno-prettify
Prettify contents of stdin.
Options:
-h
Display help
-a
Omit location and data in order to provide well-aligned logs
-s
Donot complain about errors in parsing logs
`
func prettifyFromIO(src io.Reader) {
buf := bufio.NewReader(src)
lineno := 0
for {
line, err := buf.ReadString('\n')
if err != nil {
break
}
lineno++
i := strings.Index(line, "{")
var prefix string
if i > 0 {
prefix = line[:i]
line = line[i:]
}
r, e := prettifier.DecodeJsonLogEntry(line)
if e != nil {
if !ignoreParseError {
fmt.Fprintf(os.Stderr, "steno-prettify: Malformed json at line %d : %s", lineno, line)
}
continue
}
s, _ := prettifier.EncodeRecord(r)
fmt.Println(fmt.Sprintf("%s%s", prefix, string(s)))
}
}
func prettifyFromFile(logFile string) error {
f, e := os.Open(logFile)
if e != nil {
return e
}
defer f.Close()
prettifyFromIO(f)
return nil
}
func main() {
excludedFields := gosteno.EXCLUDE_NONE
h := flag.Bool("h", false, "Show help")
a := flag.Bool("a", false, "Omit location and data in order to provide well-aligned logs")
s := flag.Bool("s", false, "Ignore errors in parsing logs")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, helptext)
}
flag.Parse()
if *h {
flag.Usage()
return
}
if *a {
excludedFields |= gosteno.EXCLUDE_FILE | gosteno.EXCLUDE_LINE | gosteno.EXCLUDE_METHOD | gosteno.EXCLUDE_DATA
}
if *s {
ignoreParseError = true
}
prettifier = gosteno.NewJsonPrettifier(excludedFields)
args := flag.Args()
if len(args) > 0 {
for _, f := range args {
if f == "-" {
prettifyFromIO(os.Stdin)
} else {
e := prettifyFromFile(f)
if e != nil {
fmt.Fprintln(os.Stderr, e)
}
}
}
} else {
prettifyFromIO(os.Stdin)
}
}