logrus/text_formatter.go

87 lines
1.8 KiB
Go
Raw Normal View History

2014-03-11 03:22:08 +04:00
package logrus
import (
"bytes"
2014-03-11 03:22:08 +04:00
"fmt"
"sort"
"strings"
"time"
2014-03-11 03:22:08 +04:00
)
const (
nocolor = 0
red = 31
green = 32
yellow = 33
blue = 34
)
func init() {
baseTimestamp = time.Now()
}
func miniTS() int {
return int(time.Since(baseTimestamp) / time.Second)
}
2014-03-11 03:22:08 +04:00
type TextFormatter struct {
// Set to true to bypass checking for a TTY before outputting colors.
ForceColors bool
DisableColors bool
2014-03-11 03:22:08 +04:00
}
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
b := &bytes.Buffer{}
2014-03-11 03:22:08 +04:00
2014-07-27 06:22:39 +04:00
prefixFieldClashes(entry)
if (f.ForceColors || IsTerminal()) && !DisableColors {
levelText := strings.ToUpper(entry.Data["level"].(string))[0:4]
2014-03-11 03:22:08 +04:00
levelColor := blue
if entry.Data["level"] == "warning" {
levelColor = yellow
} else if entry.Data["level"] == "error" ||
entry.Data["level"] == "fatal" ||
entry.Data["level"] == "panic" {
levelColor = red
}
2014-03-11 03:22:08 +04:00
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Data["msg"])
2014-03-11 03:22:08 +04:00
keys := make([]string, 0)
for k, _ := range entry.Data {
if k != "level" && k != "time" && k != "msg" {
keys = append(keys, k)
}
2014-03-11 03:22:08 +04:00
}
sort.Strings(keys)
for _, k := range keys {
v := entry.Data[k]
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%v", levelColor, k, v)
}
} else {
f.AppendKeyValue(b, "time", entry.Data["time"].(string))
f.AppendKeyValue(b, "level", entry.Data["level"].(string))
f.AppendKeyValue(b, "msg", entry.Data["msg"].(string))
for key, value := range entry.Data {
if key != "time" && key != "level" && key != "msg" {
f.AppendKeyValue(b, key, value)
}
2014-03-11 03:22:08 +04:00
}
}
b.WriteByte('\n')
return b.Bytes(), nil
2014-03-11 03:22:08 +04:00
}
func (f *TextFormatter) AppendKeyValue(b *bytes.Buffer, key, value interface{}) {
if _, ok := value.(string); ok {
fmt.Fprintf(b, "%v=%q ", key, value)
} else {
fmt.Fprintf(b, "%v=%v ", key, value)
}
}