From 946df89fa622324cdf80f8b0d7a3c250bc738bf2 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 6 Mar 2020 11:59:46 -0800 Subject: [PATCH] types/logger: add adapters for Logf to std Logger/Writer --- types/logger/logger.go | 22 ++++++++++++++++++++++ types/logger/logger_test.go | 21 +++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 types/logger/logger_test.go diff --git a/types/logger/logger.go b/types/logger/logger.go index bd335bd98..c48c8499f 100644 --- a/types/logger/logger.go +++ b/types/logger/logger.go @@ -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 +} diff --git a/types/logger/logger_test.go b/types/logger/logger_test.go new file mode 100644 index 000000000..b6ecee403 --- /dev/null +++ b/types/logger/logger_test.go @@ -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") +}