Skip to content

Commit

Permalink
log_writer feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
EronWright committed May 10, 2024
1 parent be74e8b commit ff22a11
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
2 changes: 1 addition & 1 deletion provider/pkg/helm/tool.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
35 changes: 24 additions & 11 deletions provider/pkg/logging/log_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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()
Expand Down

0 comments on commit ff22a11

Please sign in to comment.