修复缺失日志标识格式
Some checks are pending
Security Checks / security (push) Waiting to run

避免没有请求日志标识时输出 %!s(<nil>),并补充日志格式化回归测试。
This commit is contained in:
smail 2026-09-30 15:05:44 +08:00
parent bcf660e459
commit 7e792b1608
2 changed files with 39 additions and 1 deletions

View File

@ -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 {

View File

@ -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(<nil>)")) {
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()