-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathjson_formatter.go
71 lines (59 loc) · 1.32 KB
/
json_formatter.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
package formatters
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/subchen/go-log"
)
// JSONFormatter is a json formatter
type JSONFormatter struct {
AppName string
TimeFormat string
init sync.Once
host string
pid int
}
// Format implements log.Formatter
func (f *JSONFormatter) Format(level log.Level, msg string, logger *log.Logger) []byte {
// output fields: time level host app pid file line msg
f.init.Do(func() {
if f.AppName == "" {
f.AppName = filepath.Base(os.Args[0])
}
if f.TimeFormat == "" {
f.TimeFormat = "2006-01-02T15:04:05.000-0700"
}
f.host, _ = os.Hostname()
f.pid = os.Getpid()
})
data := make(map[string]interface{}, 8)
// file, line
file, line := FilelineCaller(5)
data["time"] = time.Now().Format(f.TimeFormat)
data["level"] = level.String()
data["host"] = f.host
data["app"] = f.AppName
data["pid"] = f.pid
data["file"] = file
data["line"] = line
data["msg"] = msg
serialized, err := marshal(data)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to marshal json, %v\n", err)
}
return serialized
}
func marshal(v interface{}) ([]byte, error) {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
err := encoder.Encode(v)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}