-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
85 lines (70 loc) · 1.75 KB
/
main.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
// This program takes the structured log output and makes it readable.
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"strings"
)
var service string
func init() {
flag.StringVar(&service, "service", "", "filter which service to see")
}
func main() {
flag.Parse()
var b strings.Builder
service := strings.ToLower(service)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
s := scanner.Text()
m := make(map[string]any)
err := json.Unmarshal([]byte(s), &m)
if err != nil {
if service == "" {
fmt.Println(s)
}
continue
}
// If a service filter was provided, check.
if service != "" && strings.ToLower(m["service"].(string)) != service {
continue
}
// I like always having a traceid present in the logs.
traceID := "00000000-0000-0000-0000-000000000000"
if v, ok := m["trace_id"]; ok {
traceID = fmt.Sprintf("%v", v)
}
// {"time":"2023-06-01T17:21:11.13704718Z","level":"INFO","msg":"startup","service":"SALES-API","GOMAXPROCS":1}
// Build out the know portions of the log in the order
// I want them in.
b.Reset()
b.WriteString(fmt.Sprintf("%s: %s: %s: %s: %s: %s: ",
m["service"],
m["time"],
m["file"],
m["level"],
traceID,
m["msg"],
))
// Add the rest of the keys ignoring the ones we already
// added for the log.
for k, v := range m {
switch k {
case "service", "time", "file", "level", "trace_id", "msg":
continue
}
// It's nice to see the key[value] in this format
// especially since map ordering is random.
b.WriteString(fmt.Sprintf("%s[%v]: ", k, v))
}
// Write the new log format, removing the last :
out := b.String()
fmt.Println(out[:len(out)-2])
}
if err := scanner.Err(); err != nil {
log.Println(err)
}
}