diff --git a/alog_test.go b/alog_test.go index 0d3b3fb..fa1b4c4 100644 --- a/alog_test.go +++ b/alog_test.go @@ -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) + } +} diff --git a/logger.go b/logger.go index 6dd2519..b484aef 100644 --- a/logger.go +++ b/logger.go @@ -3,6 +3,7 @@ package alog import ( "context" "fmt" + "log" "runtime" "time" ) @@ -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) +}