This commit is contained in:
程广 2023-11-29 10:16:56 +08:00
parent d94313028a
commit bde229321f
5 changed files with 41 additions and 26 deletions

View File

@ -2,15 +2,14 @@ package gologger
import (
"fmt"
"strings"
)
const (
ErrorTemplate = "\033[1;31m%s\033[0m\n"
WarnTemplate = "\033[1;33m%s\033[0m\n"
InfoTemplate = "\033[1;32m%s\033[0m\n"
DebugTemplate = "\033[1;34m%s\033[0m\n"
TraceTemplate = "\033[1;35m%s\033[0m\n"
ErrorTemplate = "\033[1;31m%s\033[0m"
WarnTemplate = "\033[1;33m%s\033[0m"
InfoTemplate = "\033[1;32m%s\033[0m"
DebugTemplate = "\033[1;34m%s\033[0m"
TraceTemplate = "\033[1;35m%s\033[0m"
)
type ConsoleAppender struct {
@ -21,17 +20,8 @@ func (c *ConsoleAppender) GetName() string {
}
func (c *ConsoleAppender) Append(logEvent LogEvent) {
data := []interface{}{
logEvent.Ts.Format("2006-01-02 15:04:05"),
" ",
}
dmsg := fmt.Sprint(logEvent.Data)
dmsg = strings.TrimLeft(dmsg, "[")
dmsg = strings.TrimRight(dmsg, "]")
data = append(data, "["+logEvent.Category+"] ")
data = append(data, dmsg)
logMsg := fmt.Sprint(data...)
logMsg := format(logEvent)
switch logEvent.Level {
case Error:
fmt.Printf(ErrorTemplate, logMsg)

12
file.go
View File

@ -1,7 +1,6 @@
package gologger
import (
"fmt"
"os"
"path/filepath"
)
@ -25,15 +24,8 @@ func (f *FileAppender) Append(logEvent LogEvent) {
f.file, _ = os.OpenFile(f.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
}
data := []interface{}{
logEvent.Ts.Format("2006-01-02 15:04:05"),
" ",
}
data = append(data, "["+logEvent.Category+"] ")
dmsg := fmt.Sprint(logEvent.Data...)
data = append(data, dmsg)
logMsg := fmt.Sprint(data...)
f.file.WriteString(logMsg + "\n")
logMsg := format(logEvent)
f.file.WriteString(logMsg)
}

23
format.go Normal file
View File

@ -0,0 +1,23 @@
package gologger
import (
"fmt"
)
const logTemplate = "[%s] %s - %s\n"
func format(logEvent LogEvent) string {
data := logEvent.Ts.Format("2006-01-02 15:04:05")
msg := fmt.Sprint(logEvent.Data...)
ret := fmt.Sprintf(logTemplate, data, getLogLevelStr(logEvent.Level), msg)
return ret
}
func getLogLevelStr(level int) string {
for name, slevel := range logLevelMap {
if slevel == level {
return name
}
}
return "Unknown"
}

9
log/fat.log Normal file
View File

@ -0,0 +1,9 @@
[2023-11-29 10:09:22] debug - [debug]
[2023-11-29 10:09:22] debug - [debug again]
[2023-11-29 10:09:22] error - [This is error]
[2023-11-29 10:12:22] debug - debug
[2023-11-29 10:12:22] debug - debug again
[2023-11-29 10:12:22] error - This is error
[2023-11-29 10:13:18] debug - debug
[2023-11-29 10:13:18] debug - debug again
[2023-11-29 10:13:18] error - This is error

View File

@ -118,6 +118,7 @@ func makeLogger(name string, config LogConfig) Logger {
logger := &Logger{category: name}
levelstr := strings.ToLower(config.Level)
logger.level = logLevelMap[levelstr]
if config.Appenders == nil || len(config.Appenders) == 0 {
logger.appenders = []LoggerAppender{consoleAppender}
} else {