gologger/format.go

54 lines
1.0 KiB
Go

package gologger
import (
"fmt"
"strings"
)
const logTemplate = "[%s] %s : %s - %s\n"
func format(logEvent LogEvent) string {
data := logEvent.Ts.Format("2006-01-02 15:04:05")
msg := ""
firstMsg := logEvent.Data[0]
if isFormatString(firstMsg) {
msg = fmt.Sprintf(firstMsg.(string), logEvent.Data[1:]...)
} else {
msg = sprint(logEvent.Data)
}
ret := fmt.Sprintf(logTemplate, data, logEvent.Category, getLogLevelStr(logEvent.Level), msg)
return ret
}
func getLogLevelStr(level int) string {
for name, slevel := range logLevelMap {
if slevel == level {
return strings.ToUpper(name)
}
}
return "Unknown"
}
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...)
}