-
Notifications
You must be signed in to change notification settings - Fork 2
/
textformatter.go
157 lines (118 loc) · 3.81 KB
/
textformatter.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package loggerus
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
"golang.org/x/tools/container/intsets"
)
type TextFormatter struct {
maxVariableLen int
enrichWhoField bool
}
func NewTextFormatter(maxVariableLen int, enrichWhoField bool) (*TextFormatter, error) {
color.NoColor = false
return &TextFormatter{
maxVariableLen: maxVariableLen,
enrichWhoField: enrichWhoField,
}, nil
}
func (f *TextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
buffer := bytes.NewBuffer([]byte{})
// write date
buffer.WriteString(color.WhiteString(entry.Time.Format("02-01-06 15:04:05.000"))) // nolint: errcheck
// write logger name
if f.enrichWhoField {
buffer.WriteString(" " + color.CyanString(f.getFormattedWho(entry.Data))) // nolint: errcheck
}
// write level
buffer.WriteString(" " + f.getLevelOutput(entry.Level)) // nolint: errcheck
// write message
buffer.WriteString(" " + entry.Message) // nolint: errcheck
// write fields
buffer.WriteString(f.getFieldsOutput(entry.Data)) // nolint: errcheck
// add newline
buffer.WriteByte('\n') // nolint: errcheck
return buffer.Bytes(), nil
}
func (f *TextFormatter) getLevelOutput(level logrus.Level) string {
switch level {
case logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel:
return color.HiRedString("(E)")
case logrus.WarnLevel:
return color.HiYellowString("(W)")
case logrus.InfoLevel:
return color.HiBlueString("(I)")
case logrus.DebugLevel:
return color.GreenString("(D)")
case logrus.TraceLevel:
return color.GreenString("(T)")
}
return color.RedString("(?)")
}
func (f *TextFormatter) getFieldsOutput(fields logrus.Fields) string {
maxVariableLen := f.maxVariableLen
if maxVariableLen == 0 {
maxVariableLen = intsets.MaxInt
}
// remove context - it shouldn't be printed
delete(fields, "ctx")
singleLineKV := map[string]string{}
blockKV := map[string]string{}
for fieldKey, fieldValue := range fields {
// if we're dealing with a struct, use json
switch reflect.Indirect(reflect.ValueOf(fieldValue)).Kind() {
case reflect.Slice, reflect.Map, reflect.Struct:
fieldValueBytes, _ := json.Marshal(fieldValue)
// if it's short - add to single line. otherwise to block
if len(fieldValueBytes) <= maxVariableLen {
singleLineKV[fieldKey] = string(fieldValueBytes)
} else {
blockBuffer := bytes.NewBuffer([]byte{})
if err := json.Indent(blockBuffer, fieldValueBytes, "", "\t"); err != nil {
blockBuffer.WriteString(fmt.Sprintf("Failed to encode: %s", err.Error())) // nolint: errcheck
}
blockKV[fieldKey] = blockBuffer.String()
}
case reflect.String:
stringFieldValue := fmt.Sprintf("%s", fieldValue)
// if there are newlines in output, add to block
if strings.Contains(stringFieldValue, "\n") {
blockKV[fieldKey] = stringFieldValue
} else {
singleLineKV[fieldKey] = fmt.Sprintf(`"%s"`, fieldValue)
}
default:
singleLineKV[fieldKey] = fmt.Sprintf("%v", fieldValue)
}
}
fieldsOutput := ""
if len(singleLineKV) != 0 {
fieldsOutput = color.WhiteString(" :: ")
}
separator := color.WhiteString(" || ")
for singleLineKey, singleLineValue := range singleLineKV {
fieldsOutput += fmt.Sprintf("%s=%s%s", color.BlueString(singleLineKey), singleLineValue, separator)
}
// remove last ||
fieldsOutput = strings.TrimSuffix(fieldsOutput, separator)
if len(blockKV) != 0 {
for blockKey, blockValue := range blockKV {
fieldsOutput += fmt.Sprintf("\n* %s:\n", color.BlueString(blockKey))
fieldsOutput += blockValue
fieldsOutput += "\n"
}
}
return fieldsOutput
}
func (f *TextFormatter) getFormattedWho(data logrus.Fields) string {
who, ok := data["who"]
if ok {
whoStr := fmt.Sprintf("%20s", who)
return fmt.Sprintf("%20s", whoStr[len(whoStr)-20:])
}
return fmt.Sprintf("%20s", "")
}