From ff22a113eb53d71dd20670884fb9dd99dd03eff9 Mon Sep 17 00:00:00 2001 From: Eron Wright Date: Fri, 10 May 2024 10:56:11 -0700 Subject: [PATCH] log_writer feedback --- provider/pkg/helm/tool.go | 2 +- provider/pkg/logging/log_writer.go | 35 ++++++++++++++++++++---------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/provider/pkg/helm/tool.go b/provider/pkg/helm/tool.go index 7c0222dfbb..a4bc985fdd 100644 --- a/provider/pkg/helm/tool.go +++ b/provider/pkg/helm/tool.go @@ -338,7 +338,7 @@ func debug(format string, a ...any) { func debugStream() *logging.LogWriter { // FUTURE: set log depth - return logging.NewLogWriterPrefixed(logger.V(6).Infof, "[helm] ") + return logging.NewLogWriter(logger.V(6).Infof, logging.WithPrefix("[helm] ")) } // defaultKeyring returns the expanded path to the default keyring. diff --git a/provider/pkg/logging/log_writer.go b/provider/pkg/logging/log_writer.go index 9413a2a2a4..82777eeb0a 100644 --- a/provider/pkg/logging/log_writer.go +++ b/provider/pkg/logging/log_writer.go @@ -20,10 +20,11 @@ import ( "sync" ) -// logWriter is an io.Writer that writes to a logging function, buffering as necessary. - +// logF is an abstract logging function that accepts a format string and arguments. +// The function is expected to write a newline after each message. type logF func(format string, args ...interface{}) +// logWriter is an io.Writer that writes to a logging function, buffering as necessary. type LogWriter struct { l logF prefix string @@ -34,7 +35,20 @@ type LogWriter struct { mu sync.Mutex // guards buff } -var _ io.Writer = (*LogWriter)(nil) +type Option interface { + apply(*LogWriter) +} + +type prefixOption string + +func (p prefixOption) apply(l *LogWriter) { + l.prefix = string(p) +} + +// WithPrefix prepends the given prefix to each line. +func WithPrefix(prefix string) Option { + return prefixOption(prefix) +} // NewLogWriter builds and returns an io.Writer that // writes messages to the given logging function. @@ -44,16 +58,15 @@ var _ io.Writer = (*LogWriter)(nil) // is flushed when the writer flushes. // // The returned writer is safe for concurrent use. -func NewLogWriter(l logF) *LogWriter { - return NewLogWriterPrefixed(l, "") +func NewLogWriter(l logF, opts ...Option) *LogWriter { + w := &LogWriter{l: l} + for _, o := range opts { + o.apply(w) + } + return w } -// NewLogWriterPrefixed is a variant of LogWriter -// that prepends the given prefix to each line. -func NewLogWriterPrefixed(l logF, prefix string) *LogWriter { - w := LogWriter{l: l, prefix: prefix} - return &w -} +var _ io.Writer = (*LogWriter)(nil) func (w *LogWriter) Write(bs []byte) (int, error) { w.mu.Lock()