From 7509b6c8c66ac68994e668d193c272d2c0c18038 Mon Sep 17 00:00:00 2001 From: zhaoyupeng Date: Thu, 12 Jun 2025 18:05:05 +0800 Subject: [PATCH] feat: logctx add default uuid --- logger/ctx.go | 57 ++++++++++++++++++++-------------------------- logger/ctx_test.go | 5 +++- 2 files changed, 29 insertions(+), 33 deletions(-) diff --git a/logger/ctx.go b/logger/ctx.go index 7c428d8..22ca6d0 100644 --- a/logger/ctx.go +++ b/logger/ctx.go @@ -1,57 +1,50 @@ package logger -import "context" +import ( + "context" + "gitea.loveuer.com/yizhisec/packages/opt" + uuid2 "github.com/google/uuid" +) + +func traceId(ctx context.Context) string { + if ctx == nil { + uuid, _ := uuid2.NewV7() + return uuid.String() + } + + if id, _ := ctx.Value(opt.TraceKey).(string); id != "" { + return id + } + + uuid, _ := uuid2.NewV7() + return uuid.String() +} func DebugCtx(ctx context.Context, msg string, data ...any) { - trace := "nil" - if ctx != nil { - trace, _ = ctx.Value("trace").(string) - } - msg = "[" + trace + "] " + msg - + msg = "[" + traceId(ctx) + "] " + msg DefaultLogger.Debug(msg, data...) } func InfoCtx(ctx context.Context, msg string, data ...any) { - trace := "nil" - if ctx != nil { - trace, _ = ctx.Value("trace").(string) - } - msg = "[" + trace + "] " + msg + msg = "[" + traceId(ctx) + "] " + msg DefaultLogger.Info(msg, data...) } func WarnCtx(ctx context.Context, msg string, data ...any) { - trace := "nil" - if ctx != nil { - trace, _ = ctx.Value("trace").(string) - } - msg = "[" + trace + "] " + msg + msg = "[" + traceId(ctx) + "] " + msg DefaultLogger.Warn(msg, data...) } func ErrorCtx(ctx context.Context, msg string, data ...any) { - trace := "nil" - if ctx != nil { - trace, _ = ctx.Value("trace").(string) - } - msg = "[" + trace + "] " + msg + msg = "[" + traceId(ctx) + "] " + msg DefaultLogger.Error(msg, data...) } func PanicCtx(ctx context.Context, msg string, data ...any) { - trace := "nil" - if ctx != nil { - trace, _ = ctx.Value("trace").(string) - } - msg = "[" + trace + "] " + msg + msg = "[" + traceId(ctx) + "] " + msg DefaultLogger.Panic(msg, data...) } func FatalCtx(ctx context.Context, msg string, data ...any) { - trace := "nil" - if ctx != nil { - trace, _ = ctx.Value("trace").(string) - } - msg = "[" + trace + "] " + msg + msg = "[" + traceId(ctx) + "] " + msg DefaultLogger.Fatal(msg, data...) } diff --git a/logger/ctx_test.go b/logger/ctx_test.go index 269e8d2..f503d1e 100644 --- a/logger/ctx_test.go +++ b/logger/ctx_test.go @@ -11,5 +11,8 @@ func TestCtxLog(t *testing.T) { InfoCtx(nil, "hello %s", "world") WarnCtx(context.Background(), "hello %s", "world") ctx := context.Background() - context.WithValue(ctx, opt.TraceKey, "value") + ctx = context.WithValue(ctx, opt.TraceKey, "value") + SetLogLevel(LogLevelDebug) + DebugCtx(ctx, "hello %s", "world") + ErrorCtx(ctx, "hello %s", "world") }