github.com/avicd/go-utilx@v0.1.0/logx/console.go (about) 1 package logx 2 3 import ( 4 "fmt" 5 "log" 6 ) 7 8 var Colors = map[Level]string{ 9 DEBUG: "34", 10 INFO: "32", 11 WARN: "33", 12 ERROR: "31", 13 FATAL: "35", 14 } 15 16 type ConsoleAppender struct { 17 logger *log.Logger 18 Prefix string 19 TimeLayout string 20 ColorOff bool 21 ColorKind CKind 22 Colors map[Level]string 23 } 24 25 func (it *ConsoleAppender) getLogger() *log.Logger { 26 if it.logger == nil { 27 it.logger = log.New(log.Writer(), it.Prefix, 0) 28 } 29 return it.logger 30 } 31 32 func (it *ConsoleAppender) Write(level Level, args ...any) { 33 label := Labels[level] + " " 34 color := it.Colors[level] 35 var dest []any 36 if !it.ColorOff { 37 if color == "" { 38 color = Colors[level] 39 } 40 switch it.ColorKind { 41 case CLabel: 42 dest = append(dest, timeNow(it.TimeLayout)) 43 label = fmt.Sprintf("\033[%sm%s\033[0m", color, label) 44 dest = append(dest, label) 45 dest = append(dest, args...) 46 case CMsg: 47 dest = append(dest, timeNow(it.TimeLayout)) 48 dest = append(dest, label) 49 dest = append(dest, fmt.Sprintf("\033[%sm", color)) 50 dest = append(dest, args...) 51 dest = append(dest, "\033[0m") 52 case CLabelMsg: 53 dest = append(dest, timeNow(it.TimeLayout)) 54 dest = append(dest, fmt.Sprintf("\033[%sm", color)) 55 dest = append(dest, label) 56 dest = append(dest, args...) 57 dest = append(dest, "\033[0m") 58 case CAll: 59 dest = append(dest, fmt.Sprintf("\033[%sm", color)) 60 dest = append(dest, timeNow(it.TimeLayout)) 61 dest = append(dest, label) 62 dest = append(dest, args...) 63 dest = append(dest, "\033[0m") 64 } 65 } 66 it.getLogger().Print(dest...) 67 }