github.com/kolbycrouch/elvish@v0.14.1-0.20210614162631-215b9ac1c423/pkg/logutil/logutil.go (about)

     1  // Package logutil provides logging utilities.
     2  package logutil
     3  
     4  import (
     5  	"io"
     6  	"io/ioutil"
     7  	"log"
     8  	"os"
     9  )
    10  
    11  var (
    12  	out = ioutil.Discard
    13  	// If out is set by SetOutputFile, outFile is set and keeps the same value
    14  	// as out. Otherwise, outFile is nil.
    15  	outFile *os.File
    16  	loggers []*log.Logger
    17  )
    18  
    19  // GetLogger gets a logger with a prefix.
    20  func GetLogger(prefix string) *log.Logger {
    21  	logger := log.New(out, prefix, log.LstdFlags)
    22  	loggers = append(loggers, logger)
    23  	return logger
    24  }
    25  
    26  // SetOutput redirects the output of all loggers obtained with GetLogger to the
    27  // new io.Writer. If the old output was a file opened by SetOutputFile, it is
    28  // closed.
    29  func SetOutput(newout io.Writer) {
    30  	if outFile != nil {
    31  		outFile.Close()
    32  		outFile = nil
    33  	}
    34  	out = newout
    35  	outFile = nil
    36  	for _, logger := range loggers {
    37  		logger.SetOutput(out)
    38  	}
    39  }
    40  
    41  // SetOutputFile redirects the output of all loggers obtained with GetLogger to
    42  // the named file. If the old output was a file opened by SetOutputFile, it is
    43  // closed. The new file is truncated. SetOutFile("") is equivalent to
    44  // SetOutput(ioutil.Discard).
    45  func SetOutputFile(fname string) error {
    46  	if fname == "" {
    47  		SetOutput(ioutil.Discard)
    48  		return nil
    49  	}
    50  	file, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	SetOutput(file)
    55  	outFile = file
    56  	return nil
    57  }