feat: logctx add default uuid
This commit is contained in:
parent
4eb256bc78
commit
7509b6c8c6
@ -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...)
|
||||
}
|
||||
|
@ -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")
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user