From 7e792b1608cbc137fce0ec3783423647124713ff Mon Sep 17 00:00:00 2001 From: smail Date: Wed, 30 Sep 2026 15:05:44 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=BC=BA=E5=A4=B1=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E6=A0=87=E8=AF=86=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 避免没有请求日志标识时输出 %!s(),并补充日志格式化回归测试。 --- backend/config/config.go | 4 ++- backend/config/config_security_test.go | 36 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/backend/config/config.go b/backend/config/config.go index 23a1023..6ff7f14 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -153,7 +153,9 @@ func (l *logFormatter) Format(entry *log.Entry) ([]byte, error) { if entry.Context != nil { ctx, ok := entry.Context.(*context.Context) if ok && ctx != nil { - b.WriteString(fmt.Sprintf("[%s]", ctx.GetValue(context.LogID))) + if logID := ctx.GetValue(context.LogID); logID != nil { + b.WriteString(fmt.Sprintf("[%v]", logID)) + } } } if entry.Caller != nil { diff --git a/backend/config/config_security_test.go b/backend/config/config_security_test.go index 5e5431f..15f706b 100644 --- a/backend/config/config_security_test.go +++ b/backend/config/config_security_test.go @@ -2,12 +2,48 @@ package config import ( "bytes" + stdcontext "context" "encoding/json" "os" "path/filepath" "testing" + + appcontext "git.pcux.cn/xuans/Smail/utils/context" + log "github.com/sirupsen/logrus" ) +func TestLogFormatterHandlesMissingLogID(t *testing.T) { + entry := &log.Entry{ + Context: &appcontext.Context{Context: stdcontext.Background()}, + Message: "配置操作", + } + + output, err := (&logFormatter{}).Format(entry) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(output, []byte("%!s()")) { + t.Fatalf("log output contains a formatting error: %q", output) + } + if !bytes.Contains(output, []byte("配置操作")) { + t.Fatalf("log output lost the message: %q", output) + } +} + +func TestLogFormatterIncludesLogID(t *testing.T) { + ctx := &appcontext.Context{Context: stdcontext.Background()} + ctx.SetValue(appcontext.LogID, "request-123") + entry := &log.Entry{Context: ctx, Message: "配置操作"} + + output, err := (&logFormatter{}).Format(entry) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(output, []byte("[request-123]")) { + t.Fatalf("log output lost the log ID: %q", output) + } +} + func TestConfigCredentialsAreEncryptedAtRest(t *testing.T) { oldRoot := ROOT_PATH root := t.TempDir()