types/logger: add adapters for Logf to std Logger/Writer

This commit is contained in:
Brad Fitzpatrick 2020-03-06 11:59:46 -08:00
parent 5562fae9f0
commit 946df89fa6
2 changed files with 43 additions and 0 deletions

View File

@ -7,6 +7,11 @@
// types around.
package logger
import (
"io"
"log"
)
// Logf is the basic Tailscale logger type: a printf-like func.
type Logf func(format string, args ...interface{})
@ -16,3 +21,20 @@ func WithPrefix(f Logf, prefix string) Logf {
f(prefix+format, args...)
}
}
// FuncWriter returns an io.Writer that writes to f.
func FuncWriter(f Logf) io.Writer {
return funcWriter{f}
}
// StdLogger returns a standard library logger from a Logf.
func StdLogger(f Logf) *log.Logger {
return log.New(FuncWriter(f), "", 0)
}
type funcWriter struct{ f Logf }
func (w funcWriter) Write(p []byte) (int, error) {
w.f("%s", p)
return len(p), nil
}

View File

@ -0,0 +1,21 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package logger
import (
"log"
"testing"
)
func TestFuncWriter(t *testing.T) {
w := FuncWriter(t.Logf)
lg := log.New(w, "prefix: ", 0)
lg.Printf("plumbed through")
}
func TestStdLogger(t *testing.T) {
lg := StdLogger(t.Logf)
lg.Printf("plumbed through")
}