gologger/format.go

54 lines
1.0 KiB
Go
Raw Permalink Normal View History

2023-11-29 10:16:56 +08:00
package gologger
import (
"fmt"
2024-10-01 13:47:50 +08:00
"strings"
2023-11-29 10:16:56 +08:00
)
const logTemplate = "[%s] %s : %s - %s\n"
2023-11-29 10:16:56 +08:00
func format(logEvent LogEvent) string {
data := logEvent.Ts.Format("2006-01-02 15:04:05")
2024-10-01 13:47:50 +08:00
msg := ""
firstMsg := logEvent.Data[0]
if isFormatString(firstMsg) {
msg = fmt.Sprintf(firstMsg.(string), logEvent.Data[1:]...)
} else {
msg = sprint(logEvent.Data)
}
2023-12-10 00:40:49 +08:00
ret := fmt.Sprintf(logTemplate, data, logEvent.Category, getLogLevelStr(logEvent.Level), msg)
2023-11-29 10:16:56 +08:00
return ret
}
func getLogLevelStr(level int) string {
for name, slevel := range logLevelMap {
if slevel == level {
2024-10-01 13:47:50 +08:00
return strings.ToUpper(name)
2023-11-29 10:16:56 +08:00
}
}
return "Unknown"
}
2024-10-01 13:47:50 +08:00
func isFormatString(f interface{}) bool {
s, ok := f.(string)
if !ok {
return false
}
// 尝试使用空接口来格式化字符串
m := fmt.Sprintf(s, []interface{}{})
return strings.Index(m, "MISSING") != -1
}
func sprint(s []interface{}) string {
str := make([]any, len(s))
for i, v := range s {
if i > 0 {
str[i] = fmt.Sprintf(" %v", v)
} else {
str[i] = fmt.Sprintf("%v", v)
}
}
return fmt.Sprint(str...)
}