package log import ( "context" "log/slog" "os" "strings" ) type ctxKey string const requestIDKey ctxKey = "request_id" func Setup(level string) *slog.Logger { var lvl slog.Level switch strings.ToLower(level) { case "debug": lvl = slog.LevelDebug case "warn": lvl = slog.LevelWarn case "error": lvl = slog.LevelError default: lvl = slog.LevelInfo } h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: lvl}) logger := slog.New(h) slog.SetDefault(logger) return logger } func WithRequestID(ctx context.Context, id string) context.Context { return context.WithValue(ctx, requestIDKey, id) } func RequestID(ctx context.Context) string { if v, ok := ctx.Value(requestIDKey).(string); ok { return v } return "" } func From(ctx context.Context) *slog.Logger { if id := RequestID(ctx); id != "" { return slog.Default().With("request_id", id) } return slog.Default() }