diff options
Diffstat (limited to 'device/logger.go')
-rw-r--r-- | device/logger.go | 67 |
1 files changed, 28 insertions, 39 deletions
diff --git a/device/logger.go b/device/logger.go index 3c4d744..a2adea3 100644 --- a/device/logger.go +++ b/device/logger.go @@ -1,59 +1,48 @@ /* SPDX-License-Identifier: MIT * - * Copyright (C) 2017-2020 WireGuard LLC. All Rights Reserved. + * Copyright (C) 2017-2025 WireGuard LLC. All Rights Reserved. */ package device import ( - "io" - "io/ioutil" "log" "os" ) +// A Logger provides logging for a Device. +// The functions are Printf-style functions. +// They must be safe for concurrent use. +// They do not require a trailing newline in the format. +// If nil, that level of logging will be silent. +type Logger struct { + Verbosef func(format string, args ...any) + Errorf func(format string, args ...any) +} + +// Log levels for use with NewLogger. const ( LogLevelSilent = iota LogLevelError - LogLevelInfo - LogLevelDebug + LogLevelVerbose ) -type Logger struct { - Debug *log.Logger - Info *log.Logger - Error *log.Logger -} +// Function for use in Logger for discarding logged lines. +func DiscardLogf(format string, args ...any) {} +// NewLogger constructs a Logger that writes to stdout. +// It logs at the specified log level and above. +// It decorates log lines with the log level, date, time, and prepend. func NewLogger(level int, prepend string) *Logger { - output := os.Stdout - logger := new(Logger) - - logErr, logInfo, logDebug := func() (io.Writer, io.Writer, io.Writer) { - if level >= LogLevelDebug { - return output, output, output - } - if level >= LogLevelInfo { - return output, output, ioutil.Discard - } - if level >= LogLevelError { - return output, ioutil.Discard, ioutil.Discard - } - return ioutil.Discard, ioutil.Discard, ioutil.Discard - }() - - logger.Debug = log.New(logDebug, - "DEBUG: "+prepend, - log.Ldate|log.Ltime, - ) - - logger.Info = log.New(logInfo, - "INFO: "+prepend, - log.Ldate|log.Ltime, - ) - logger.Error = log.New(logErr, - "ERROR: "+prepend, - log.Ldate|log.Ltime, - ) + logger := &Logger{DiscardLogf, DiscardLogf} + logf := func(prefix string) func(string, ...any) { + return log.New(os.Stdout, prefix+": "+prepend, log.Ldate|log.Ltime).Printf + } + if level >= LogLevelVerbose { + logger.Verbosef = logf("DEBUG") + } + if level >= LogLevelError { + logger.Errorf = logf("ERROR") + } return logger } |