github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/cmds/core/elvish/util/log.go (about) 1 package util 2 3 import ( 4 "io" 5 "io/ioutil" 6 "log" 7 "os" 8 ) 9 10 var ( 11 out io.Writer = ioutil.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 outFile = nil 35 for _, logger := range loggers { 36 logger.SetOutput(out) 37 } 38 } 39 40 // SetOutputFile redirects the output of all loggers obtained with GetLogger to 41 // the named file. If the old output was a file opened by SetOutputFile, it is 42 // closed. The new file is truncated. SetOutFile("") is equivalent to 43 // SetOutput(ioutil.Discard). 44 func SetOutputFile(fname string) error { 45 if fname == "" { 46 SetOutput(ioutil.Discard) 47 return nil 48 } 49 file, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) 50 if err != nil { 51 return err 52 } 53 SetOutput(file) 54 outFile = file 55 return nil 56 }