Spaces:
Running
Running
File size: 2,681 Bytes
a4468f1 |
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 |
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
}
|