/
tbsFormatter.go
54 lines (46 loc) · 1.44 KB
/
tbsFormatter.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
package logging
import (
"encoding/json"
"fmt"
"github.com/sirupsen/logrus"
"strings"
)
const (
defaultTimestampFormat string = "2006-01-02 15:04:05.000000"
defaultLogFormat string = "%time% [%level%] [%context%] %msg% %meta%"
)
type TbsFormatter struct {
TimestampFormat string
LogFormat string
LevelPadding uint8
ContextPadding uint8
}
func (f *TbsFormatter) Format(e *logrus.Entry) ([]byte, error) {
timestampFormat := defaultTimestampFormat
if f.TimestampFormat != "" {
timestampFormat = f.TimestampFormat
}
logFormat := defaultLogFormat
if f.LogFormat != "" {
logFormat = f.LogFormat
}
line := strings.Replace(logFormat, "%time%", e.Time.Format(timestampFormat), 1)
line = strings.Replace(line, "%level%", fmt.Sprintf("%*s", f.LevelPadding, strings.ToUpper(e.Level.String())), 1)
if context, ok := e.Data["context"]; ok && context != nil {
line = strings.Replace(line, "%context%", fmt.Sprintf("%*s", f.ContextPadding, context.(string)), 1)
delete(e.Data, "context")
} else {
line = strings.Replace(line, "%context%", fmt.Sprintf("%*s", f.ContextPadding, strings.ToUpper("MissCtx")), 1)
}
line = strings.Replace(line, "%msg%", e.Message, 1)
if len(e.Data) > 0 {
meta, err := json.Marshal(e.Data)
if err != nil {
return nil, err
}
line = strings.Replace(line, "%meta%", string(meta), 1)
} else {
line = strings.Replace(line, "%meta%", "", 1)
}
return []byte(strings.TrimSpace(line) + "\n"), nil
}