Skip to content

Commit

Permalink
Add Logger.StdLogger() to get a standard log.Logger
Browse files Browse the repository at this point in the history
This is meant primarily for passing to APIs that only accept a
log.Logger as a custom logger.
  • Loading branch information
justinruggles committed Dec 19, 2018
1 parent 9d211b9 commit 1bdf0ad
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions alog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,22 @@ func TestIgnoredTag(t *testing.T) {
t.Fatalf("want: %#q, got: %#q", want, got)
}
}

func TestStdLogger(t *testing.T) {
buf := &bytes.Buffer{}
dumper := EmitterFunc(func(ctx context.Context, e *Entry) {
fmt.Fprintf(buf, "%s %v %s\n", e.Time.Format(time.RFC3339), e.Tags, e.Msg)
})

l := New(WithEmitter(dumper), OverrideTimestamp(func() time.Time { return time.Time{} }))

ctx := AddTags(context.Background(), "a", "b")
sl := l.StdLogger(ctx)
sl.Printf("test")

want := "0001-01-01T00:00:00Z [[a b]] test\n"
got := buf.String()
if got != want {
t.Fatalf("want: %#q, got: %#q", want, got)
}
}
19 changes: 19 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package alog
import (
"context"
"fmt"
"log"
"runtime"
"time"
)
Expand Down Expand Up @@ -94,3 +95,21 @@ func (l *Logger) Print(ctx context.Context, v ...interface{}) {
func (l *Logger) Printf(ctx context.Context, f string, v ...interface{}) {
l.Output(ctx, 2, fmt.Sprintf(f, v...))
}

type writerFunc func(p []byte) (int, error)

func (w writerFunc) Write(p []byte) (int, error) {
return w(p)
}

// StdLogger returns a standard log.Logger that sends log messages to this
// logger with the provided Context. The returned log.Logger should not be
// modified.
func (l *Logger) StdLogger(ctx context.Context) *log.Logger {
return log.New(writerFunc(func(p []byte) (int, error) {
// standard Logger always writes a trailing \n, so remove it
p = p[:len(p)-1]
l.Output(ctx, 4, string(p))
return len(p), nil
}), "", 0)
}

0 comments on commit 1bdf0ad

Please sign in to comment.