feat: logctx add default uuid

This commit is contained in:
zhaoyupeng 2025-06-12 18:05:05 +08:00
parent 4eb256bc78
commit 7509b6c8c6
2 changed files with 29 additions and 33 deletions

View File

@ -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...)
}

View File

@ -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")
}