Skip to content

Commit

Permalink
llog: write output to a Writer
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Koch <[email protected]>
  • Loading branch information
hugelgupf committed Feb 23, 2024
1 parent b3d14b9 commit d599844
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
28 changes: 28 additions & 0 deletions llog/levellog.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ package llog
import (
"flag"
"fmt"
"io"
"log"
"log/slog"
"math"
"strconv"
"strings"
"testing"
)

Expand Down Expand Up @@ -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...))

Check failure on line 55 in llog/levellog.go

View workflow job for this annotation

GitHub Actions / Test (1.21.x)

assignment mismatch: 1 variable but io.WriteString returns 2 values

Check failure on line 55 in llog/levellog.go

View workflow job for this annotation

GitHub Actions / Test (1.22.x)

assignment mismatch: 1 variable but io.WriteString returns 2 values

Check failure on line 55 in llog/levellog.go

View workflow job for this annotation

GitHub Actions / Test (1.22.x)

assignment mismatch: 1 variable but io.WriteString returns 2 values

Check failure on line 55 in llog/levellog.go

View workflow job for this annotation

GitHub Actions / Build (1.21.x)

assignment mismatch: 1 variable but io.WriteString returns 2 values

Check failure on line 55 in llog/levellog.go

View workflow job for this annotation

GitHub Actions / Build (1.22.x)

assignment mismatch: 1 variable but io.WriteString returns 2 values
}
}

// 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)

Expand Down
13 changes: 13 additions & 0 deletions llog/llog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit d599844

Please sign in to comment.