-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatting.go
62 lines (51 loc) · 1.39 KB
/
formatting.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
package main
import (
"bytes"
"fmt"
"os"
"regexp"
"sort"
"text/template"
"github.com/go-logfmt/logfmt"
)
// reForm is the regex used to replace format arguments with templated placeholders.
// For example, `[.time] .msg` would become `[{{.time}}] {{.msg}}`
var reForm = regexp.MustCompile(`(^|[^a-zA-Z0-9_])(\.[a-zA-Z0-9_]+)`)
// readFormat reads the incoming format string and returns a template
// that outputs in that format
func readFormat(format string) *template.Template {
if format == "" {
return nil
}
format = reForm.ReplaceAllString(format, "$1{{$2}}")
template, err := template.New("format").Option("missingkey=zero").Parse(format)
if err != nil {
fmt.Printf("Invalid format stirng %s", format)
panic(err)
}
return template
}
// formatLine accepts a format template and a parsed line and outputs the result
// to os.Stdout
func formatLine(data map[string]string, format *template.Template) {
var buf bytes.Buffer
if err := format.Execute(&buf, data); err == nil {
fmt.Println(buf.String())
}
}
// dump writes the full set of key/value pairs back out as logfmt
func dump(data map[string]string) {
enc := logfmt.NewEncoder(os.Stdout)
keys := []string{}
// first, sort the keys
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
// then encode them in sorted order
for _, k := range keys {
v, _ := data[k]
enc.EncodeKeyval(k, v)
}
enc.EndRecord()
}