github.com/cawidtu/notwireguard-go/device@v0.0.0-20230523131112-68e8e5ce9cdf/logger.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package device
     7  
     8  import (
     9  	"log"
    10  	"os"
    11  )
    12  
    13  // A Logger provides logging for a Device.
    14  // The functions are Printf-style functions.
    15  // They must be safe for concurrent use.
    16  // They do not require a trailing newline in the format.
    17  // If nil, that level of logging will be silent.
    18  type Logger struct {
    19  	Verbosef func(format string, args ...any)
    20  	Errorf   func(format string, args ...any)
    21  }
    22  
    23  // Log levels for use with NewLogger.
    24  const (
    25  	LogLevelSilent = iota
    26  	LogLevelError
    27  	LogLevelVerbose
    28  )
    29  
    30  // Function for use in Logger for discarding logged lines.
    31  func DiscardLogf(format string, args ...any) {}
    32  
    33  // NewLogger constructs a Logger that writes to stdout.
    34  // It logs at the specified log level and above.
    35  // It decorates log lines with the log level, date, time, and prepend.
    36  func NewLogger(level int, prepend string) *Logger {
    37  	logger := &Logger{DiscardLogf, DiscardLogf}
    38  	logf := func(prefix string) func(string, ...any) {
    39  		return log.New(os.Stdout, prefix+": "+prepend, log.Ldate|log.Ltime).Printf
    40  	}
    41  	if level >= LogLevelVerbose {
    42  		logger.Verbosef = logf("DEBUG")
    43  	}
    44  	if level >= LogLevelError {
    45  		logger.Errorf = logf("ERROR")
    46  	}
    47  	return logger
    48  }