gologger/format.go

88 lines
2.1 KiB
Go
Raw Normal View History

2025-06-06 19:38:01 +08:00
// Package gologger provides a simple logging implementation with multiple appenders and formatters.
// It supports console, file, and HTTP logging with customizable formats.
2023-11-29 10:16:56 +08:00
package gologger
import (
"encoding/json"
2023-11-29 10:16:56 +08:00
"fmt"
2024-10-01 13:47:50 +08:00
"strings"
2023-11-29 10:16:56 +08:00
)
2025-06-06 19:38:01 +08:00
// LogFormatter is a function type that formats a LogEvent into a string.
// Example:
2025-06-06 20:23:06 +08:00
//
// formatter := func(event LogEvent) string {
// return fmt.Sprintf("[%s] %s: %v", event.Ts.Format("2006-01-02"), event.Level, event.Data)
// }
type LogFormatter = func(LogEvent) string
2025-06-06 20:23:06 +08:00
const logTemplate = "[%s] %s : %s - %s\n"
2025-06-06 19:38:01 +08:00
// format is the default formatter that converts a LogEvent to a string using the default template.
// It handles both simple values and formatted strings.
// Template: "[timestamp] level : category - data"
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
}
// 尝试使用空接口来格式化字符串
2024-10-01 15:55:21 +08:00
m := fmt.Sprintf(s, []interface{}{}...)
2025-06-06 09:57:25 +08:00
return strings.Contains(m, "MISSING")
2024-10-01 13:47:50 +08:00
}
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...)
}
func jsonFormatter(logEvent LogEvent) string {
_, err := json.Marshal(logEvent.Data)
if err != nil {
logEvent.Data = []interface{}{fmt.Sprintf("%v", logEvent.Data)}
}
d, _ := json.Marshal(logEvent)
return string(d)
}
func SelectFormatter(formatter string) LogFormatter {
switch strings.ToLower(formatter) {
case "json":
return jsonFormatter
case "text":
return format
default:
return format
}
}