package tui import ( "context" "io" "log/slog" "strconv" "strings" "sync" "time" ) // LogLine is one log record, formatted for the log pane. type LogLine struct { Time time.Time Level slog.Level Msg string // Attrs are the record's attributes as key=value pairs. Attrs string } // LogHandler is a slog.Handler that feeds the log pane. type LogHandler struct { level slog.Level sink *sink attrs string prefix string } // sink is shared by a handler and the handlers derived from it. type sink struct { lines chan LogLine mu sync.Mutex out io.Writer // set once the TUI is gone } // NewLogHandler returns a handler for records at level or above. func NewLogHandler(level slog.Level) *LogHandler { return &LogHandler{level: level, sink: &sink{lines: make(chan LogLine, 1024)}} } // Redirect sends all further lines to w, for after the TUI exits. func (h *LogHandler) Redirect(w io.Writer) { h.sink.mu.Lock() defer h.sink.mu.Unlock() h.sink.out = w } func (h *LogHandler) Enabled(_ context.Context, l slog.Level) bool { return l >= h.level } // Handle never blocks. When the TUI falls 1024 lines behind, new lines are // dropped. func (h *LogHandler) Handle(_ context.Context, r slog.Record) error { var b strings.Builder b.WriteString(h.attrs) r.Attrs(func(a slog.Attr) bool { writeAttr(&b, h.prefix, a) return true }) l := LogLine{Time: r.Time, Level: r.Level, Msg: r.Message, Attrs: b.String()} h.sink.mu.Lock() defer h.sink.mu.Unlock() if h.sink.out != nil { _, err := io.WriteString(h.sink.out, l.Time.Format(time.TimeOnly)+" "+l.Level.String()+" "+l.Msg+" "+l.Attrs+"\n") return err } select { case h.sink.lines <- l: default: } return nil } func (h *LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { var b strings.Builder b.WriteString(h.attrs) for _, a := range attrs { writeAttr(&b, h.prefix, a) } c := *h c.attrs = b.String() return &c } func (h *LogHandler) WithGroup(name string) slog.Handler { c := *h c.prefix = h.prefix + name + "." return &c } func writeAttr(b *strings.Builder, prefix string, a slog.Attr) { v := a.Value.Resolve() if v.Kind() == slog.KindGroup { for _, g := range v.Group() { writeAttr(b, prefix+a.Key+".", g) } return } if a.Key == "" { return } s := v.String() switch v.Kind() { case slog.KindTime: s = v.Time().Local().Format(time.TimeOnly) case slog.KindDuration: s = v.Duration().Round(time.Second).String() default: // Strings, numbers and errors print as they are. } if s == "" || strings.ContainsAny(s, " =\"\n") { s = strconv.Quote(s) } if b.Len() > 0 { b.WriteByte(' ') } b.WriteString(prefix + a.Key + "=" + s) }