-
Notifications
You must be signed in to change notification settings - Fork 1
/
simple_formatter.go
81 lines (70 loc) · 1.87 KB
/
simple_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
72
73
74
75
76
77
78
79
80
81
package logdna
import (
"bytes"
"fmt"
"sort"
"github.com/sirupsen/logrus"
)
// Most of this code is taken from logrus.TextFormatter source,
// https://github.com/sirupsen/logrus/blob/master/text_formatter.go
// with some adaptations (mostly, code removal).
//
// Logrus is copyrighted by Simon Eskildsen and licensed under MIT license.
// For more details see https://github.com/sirupsen/logrus/blob/master/LICENSE
// SimpleTextFormatter is a simplified version of logrus.TextFormatter
// It only renders the message text followed with key-value pairs,
// no colors (and terminal detection) or timestamps.
type SimpleTextFormatter struct {
DisableSorting bool
QuoteEmptyFields bool
}
// Format renders a single log entry
func (f *SimpleTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
b := &bytes.Buffer{}
keys := make([]string, 0, len(entry.Data))
for k := range entry.Data {
keys = append(keys, k)
}
if !f.DisableSorting {
sort.Strings(keys)
}
_, err := fmt.Fprintf(b, "%s ", entry.Message)
if err != nil {
return nil, err
}
for _, k := range keys {
v := entry.Data[k]
_, err := fmt.Fprintf(b, " %s=", k)
if err != nil {
return nil, err
}
f.appendValue(b, v)
}
return b.Bytes(), nil
}
func (f *SimpleTextFormatter) needsQuoting(text string) bool {
if f.QuoteEmptyFields && len(text) == 0 {
return true
}
for _, ch := range text {
if !((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-' || ch == '.' || ch == '_' ||
ch == '/' || ch == '@' || ch == '^' || ch == '+') {
return true
}
}
return false
}
func (f *SimpleTextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
stringVal, ok := value.(string)
if !ok {
stringVal = fmt.Sprint(value)
}
if !f.needsQuoting(stringVal) {
b.WriteString(stringVal)
} else {
b.WriteString(fmt.Sprintf("%q", stringVal))
}
}