From d13d85181911948a3e777b65fb0ad92a52fd592d Mon Sep 17 00:00:00 2001 From: kingecg Date: Tue, 1 Oct 2024 13:47:50 +0800 Subject: [PATCH] add support for format --- format.go | 34 ++++++++++++++++++++++++++++++++-- format_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 format_test.go diff --git a/format.go b/format.go index 6f1cde3..b3960a3 100644 --- a/format.go +++ b/format.go @@ -2,13 +2,21 @@ 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 := fmt.Sprint(logEvent.Data...) + 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 } @@ -16,8 +24,30 @@ func format(logEvent LogEvent) string { func getLogLevelStr(level int) string { for name, slevel := range logLevelMap { if slevel == level { - return name + 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...) +} diff --git a/format_test.go b/format_test.go new file mode 100644 index 0000000..70b40b4 --- /dev/null +++ b/format_test.go @@ -0,0 +1,44 @@ +package gologger + +import ( + "strings" + "testing" + "time" +) + +func TestFormat(t *testing.T) { + tests := []struct { + name string + logEvent LogEvent + want string + }{ + { + name: "Info level with format string", + logEvent: LogEvent{ + Ts: time.Now(), + Category: "test_category", + Level: Info, + Data: []interface{}{"%s: %v", "key", "value"}, + }, + want: "test_category : INFO - key: value", + }, + { + name: "Error level without format string", + logEvent: LogEvent{ + Ts: time.Now(), + Category: "test_category", + Level: Error, + Data: []interface{}{"error occurred", "additional info"}, + }, + want: "test_category : ERROR - error occurred additional info", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := format(tt.logEvent); strings.Index(got, tt.want) == -1 { + t.Errorf("format() = %v, want %v", got, tt.want) + } + }) + } +}