Spaces:
Running
Running
package logx | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"github.com/sirupsen/logrus" | |
"strings" | |
) | |
type TextFormatter struct { | |
} | |
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { | |
//前景色 背景色 | |
// 30 40 黑色 | |
// 31 41 红色 | |
// 32 42 绿色 | |
// 33 43 黄色 | |
// 34 44 蓝色 | |
// 35 45 紫色 | |
// 36 46 青色 | |
// 37 47 白色 | |
var color int | |
switch entry.Level { | |
case logrus.DebugLevel, logrus.TraceLevel: | |
color = 37 | |
case logrus.WarnLevel: | |
color = 33 | |
case logrus.ErrorLevel: | |
color = 31 | |
case logrus.InfoLevel: | |
color = 36 | |
case logrus.FatalLevel: | |
color = 41 | |
case logrus.PanicLevel: | |
color = 44 | |
default: | |
color = 36 | |
} | |
var b *bytes.Buffer | |
if entry.Buffer != nil { | |
b = entry.Buffer | |
} else { | |
b = &bytes.Buffer{} | |
} | |
if entry.HasCaller() { | |
_, _ = fmt.Fprintf(b, "\u001B[%dmFunc\u001B[0m %v():%d\n", color, entry.Caller.Function, entry.Caller.Line) | |
} | |
//entry.Message = strings.TrimSuffix(entry.Message, "\n") | |
_, _ = fmt.Fprintf(b, "%s \x1b[%dm%s\x1b[0m", entry.Time.Format("2006-01-02 15:04:05:06"), | |
color, func() string { | |
level := strings.ToUpper(entry.Level.String()) | |
if len(level) < 7 { | |
for i := len(level); i < 7; i++ { | |
level += " " | |
} | |
} | |
return level | |
}()) | |
if tag, ok := entry.Data[TagKey]; ok { | |
// TAG: | |
_, _ = fmt.Fprintf(b, "\u001B[%dm%s\u001B[0m\t", 31, strings.ToUpper(tag.(string))) | |
delete(entry.Data, TagKey) | |
} | |
_, _ = fmt.Fprintf(b, " %-44s", entry.Message) | |
if schoolId, ok := entry.Data[SchoolIDKey]; ok { | |
_, _ = fmt.Fprintf(b, "[\u001B[%dm%v\u001B[0m]\t", 35, schoolId) | |
delete(entry.Data, SchoolIDKey) | |
} | |
{ | |
userId, uidOk := entry.Data[UserIDKey] | |
username, unameOk := entry.Data[UsernameKey] | |
if uidOk && unameOk { | |
// USER_ID: USERNAME: | |
_, _ = fmt.Fprintf(b, "[\u001B[%dm%v(%v)\u001B[0m]\t", 36, username, userId) | |
delete(entry.Data, UserIDKey) | |
delete(entry.Data, UsernameKey) | |
} | |
} | |
if gUuid, ok := entry.Data[GuuIDKey]; ok { | |
// TAG: | |
_, _ = fmt.Fprintf(b, "\u001B[%dm%s\u001B[0m\t", 36, gUuid) | |
delete(entry.Data, GuuIDKey) | |
} | |
if traceId, ok := entry.Data[TraceIdKey]; ok { | |
// TRACE_ID: | |
_, _ = fmt.Fprintf(b, "\u001B[%dm%s\u001B[0m\t", 34, traceId) | |
delete(entry.Data, TraceIdKey) | |
} | |
if stack, ok := entry.Data[StackKey]; ok { | |
_, _ = fmt.Fprintf(b, "\u001B[%dm%s\u001B[0m\t", 33, stack) | |
delete(entry.Data, StackKey) | |
} | |
if len(entry.Data) > 0 { | |
// DATA: | |
var buf bytes.Buffer | |
_ = json.NewEncoder(&buf).Encode(&entry.Data) | |
_, _ = fmt.Fprintf(b, "\u001B[%dm%v\u001B[0m\t", 34, strings.TrimSuffix(buf.String(), "\n")) | |
} | |
b.WriteByte('\n') | |
return b.Bytes(), nil | |
} | |