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