2014-03-11 03:22:08 +04:00
|
|
|
package logrus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"sort"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/burke/ttyutils"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
nocolor = 0
|
|
|
|
red = 31
|
|
|
|
green = 32
|
|
|
|
yellow = 33
|
|
|
|
blue = 34
|
|
|
|
)
|
|
|
|
|
|
|
|
type TextFormatter struct {
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
|
|
|
|
var serialized []byte
|
|
|
|
|
2014-03-14 21:01:06 +04:00
|
|
|
if ttyutils.IsTerminal(os.Stdout.Fd()) {
|
|
|
|
levelText := strings.ToUpper(entry.Data["level"].(string))[0:4]
|
2014-03-11 03:22:08 +04:00
|
|
|
|
2014-03-14 21:01:06 +04:00
|
|
|
levelColor := blue
|
|
|
|
|
|
|
|
if entry.Data["level"] == "warning" {
|
|
|
|
levelColor = yellow
|
|
|
|
} else if entry.Data["level"] == "fatal" ||
|
|
|
|
entry.Data["level"] == "panic" {
|
|
|
|
levelColor = red
|
|
|
|
}
|
2014-03-11 03:22:08 +04:00
|
|
|
|
|
|
|
serialized = append(serialized, []byte(fmt.Sprintf("\x1b[%dm%s\x1b[0m[%04d] %-45s ", levelColor, levelText, miniTS(), entry.Data["msg"]))...)
|
|
|
|
|
2014-03-14 21:01:06 +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
|
|
|
}
|
2014-03-14 21:01:06 +04:00
|
|
|
sort.Strings(keys)
|
|
|
|
first := true
|
|
|
|
for _, k := range keys {
|
|
|
|
v := entry.Data[k]
|
|
|
|
if first {
|
|
|
|
first = false
|
|
|
|
} else {
|
|
|
|
serialized = append(serialized, ' ')
|
|
|
|
}
|
|
|
|
serialized = append(serialized, []byte(fmt.Sprintf("\x1b[%dm%s\x1b[0m=%v", levelColor, k, v))...)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
serialized = f.AppendKeyValue(serialized, "time", entry.Data["time"].(string))
|
|
|
|
serialized = f.AppendKeyValue(serialized, "level", entry.Data["level"].(string))
|
|
|
|
serialized = f.AppendKeyValue(serialized, "msg", entry.Data["msg"].(string))
|
|
|
|
|
|
|
|
for key, value := range entry.Data {
|
|
|
|
if key != "time" && key != "level" && key != "msg" {
|
2014-03-14 21:15:01 +04:00
|
|
|
serialized = f.AppendKeyValue(serialized, key, value)
|
2014-03-14 21:01:06 +04:00
|
|
|
}
|
2014-03-11 03:22:08 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return append(serialized, '\n'), nil
|
|
|
|
}
|
2014-03-14 21:01:06 +04:00
|
|
|
|
2014-03-14 21:15:01 +04:00
|
|
|
func (f *TextFormatter) AppendKeyValue(serialized []byte, key, value interface{}) []byte {
|
2014-03-14 21:32:49 +04:00
|
|
|
if _, ok := value.(string); ok {
|
|
|
|
return append(serialized, []byte(fmt.Sprintf("%v='%v' ", key, value))...)
|
|
|
|
} else {
|
|
|
|
return append(serialized, []byte(fmt.Sprintf("%v=%v ", key, value))...)
|
|
|
|
}
|
2014-03-14 21:01:06 +04:00
|
|
|
}
|