diff --git a/llog/levellog.go b/llog/levellog.go index 5da92a5..4e23f0d 100644 --- a/llog/levellog.go +++ b/llog/levellog.go @@ -8,10 +8,12 @@ package llog import ( "flag" "fmt" + "io" "log" "log/slog" "math" "strconv" + "strings" "testing" ) @@ -39,6 +41,32 @@ type Printfer interface { Printf(format string, v ...any) } +func lineSprintf(format string, v ...any) string { + s := fmt.Sprintf(format, v...) + if strings.HasSuffix(s, "\n") { + return s + } + return s + "\n" +} + +// WritePrintf is a Printf that prints lines to w. +func WritePrintf(w io.Writer) Printf { + return func(format string, v ...any) { + _ = io.WriteString(w, lineSprintf(format, v...)) + } +} + +// MultiPrintf is a Printf that prints to all given p. +func MultiPrintf(p ...Printf) Printf { + return func(format string, v ...any) { + for _, q := range p { + if q != nil { + q(format, v...) + } + } + } +} + // Sink is the output for Logger. type Sink func(level slog.Level, format string, v ...any) diff --git a/llog/llog_test.go b/llog/llog_test.go index 6d19990..bb15f0d 100644 --- a/llog/llog_test.go +++ b/llog/llog_test.go @@ -183,3 +183,16 @@ func TestDefaults(t *testing.T) { l = Test(t) l.Debugf("more foobar") } + +func TestBufOutput(t *testing.T) { + var s strings.Builder + l := New(slog.LevelDebug, MultiPrintf(nil, t.Logf, WritePrintf(&s))) + l.Debugf("test output!") + l.Infof("test output\n\n") + + got := s.String() + want := "DEBUG test output!\nINFO test output\n\n" + if got != want { + t.Errorf("got = %v, want %v", got, want) + } +}