-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlog_json_formatter.go
46 lines (41 loc) · 1006 Bytes
/
log_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
package metrics
import (
"encoding/json"
"fmt"
"io"
"path/filepath"
"runtime"
"time"
oldlogging "github.com/whyrusleeping/go-logging"
)
// JSONFormatter implements go-logging Formatter for JSON encoded logs
type JSONFormatter struct {
}
type logRecord struct {
Timestamp time.Time `json:"timestamp"`
Level string `json:"level"`
System string `json:"system"`
Message string `json:"message"`
File string `json:"file"`
}
// Format implements go-logging Formatter
func (jf *JSONFormatter) Format(calldepth int, r *oldlogging.Record, w io.Writer) error {
var fileLine string
if calldepth > 0 {
_, file, line, ok := runtime.Caller(calldepth + 1)
if !ok {
fileLine = "???:0"
} else {
fileLine = fmt.Sprintf("%s:%d", filepath.Base(file), line)
}
}
lr := &logRecord{
Timestamp: r.Time,
Level: r.Level.String(),
System: r.Module,
Message: r.Message(),
File: fileLine,
}
encoder := json.NewEncoder(w)
return encoder.Encode(lr)
}