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

pull/152/head
Brad Fitzpatrick 5 years ago
parent 5562fae9f0
commit 946df89fa6

@ -7,6 +7,11 @@
// types around. // types around.
package logger package logger
import (
"io"
"log"
)
// Logf is the basic Tailscale logger type: a printf-like func. // Logf is the basic Tailscale logger type: a printf-like func.
type Logf func(format string, args ...interface{}) type Logf func(format string, args ...interface{})
@ -16,3 +21,20 @@ func WithPrefix(f Logf, prefix string) Logf {
f(prefix+format, args...) 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
}

@ -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")
}
Loading…
Cancel
Save