2025-05-13 02:43:00 +08:00
|
|
|
package logutil
|
|
|
|
|
|
|
|
import (
|
2025-09-03 04:09:12 +08:00
|
|
|
"context"
|
2025-05-13 02:43:00 +08:00
|
|
|
"io"
|
|
|
|
"log/slog"
|
|
|
|
"path/filepath"
|
2025-09-17 07:18:07 +08:00
|
|
|
"runtime"
|
|
|
|
"time"
|
2025-05-13 02:43:00 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const LevelTrace slog.Level = -8
|
|
|
|
|
|
|
|
func NewLogger(w io.Writer, level slog.Level) *slog.Logger {
|
|
|
|
return slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{
|
|
|
|
Level: level,
|
|
|
|
AddSource: true,
|
|
|
|
ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
|
|
|
|
switch attr.Key {
|
|
|
|
case slog.LevelKey:
|
|
|
|
switch attr.Value.Any().(slog.Level) {
|
|
|
|
case LevelTrace:
|
|
|
|
attr.Value = slog.StringValue("TRACE")
|
|
|
|
}
|
|
|
|
case slog.SourceKey:
|
|
|
|
source := attr.Value.Any().(*slog.Source)
|
|
|
|
source.File = filepath.Base(source.File)
|
|
|
|
}
|
|
|
|
return attr
|
|
|
|
},
|
|
|
|
}))
|
|
|
|
}
|
2025-09-03 04:09:12 +08:00
|
|
|
|
2025-09-17 07:18:07 +08:00
|
|
|
type key string
|
|
|
|
|
2025-09-03 04:09:12 +08:00
|
|
|
func Trace(msg string, args ...any) {
|
2025-09-17 07:18:07 +08:00
|
|
|
TraceContext(context.WithValue(context.TODO(), key("skip"), 1), msg, args...)
|
2025-09-03 04:09:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func TraceContext(ctx context.Context, msg string, args ...any) {
|
2025-09-17 07:18:07 +08:00
|
|
|
if logger := slog.Default(); logger.Enabled(ctx, LevelTrace) {
|
|
|
|
skip, _ := ctx.Value(key("skip")).(int)
|
|
|
|
pc, _, _, _ := runtime.Caller(1 + skip)
|
|
|
|
record := slog.NewRecord(time.Now(), LevelTrace, msg, pc)
|
|
|
|
record.Add(args...)
|
|
|
|
logger.Handler().Handle(ctx, record)
|
|
|
|
}
|
2025-09-03 04:09:12 +08:00
|
|
|
}
|