github.com/leeprovoost/terraform@v0.6.10-0.20160119085442-96f3f76118e7/helper/logging/logging.go (about) 1 package logging 2 3 import ( 4 "io" 5 "io/ioutil" 6 "log" 7 "os" 8 "strings" 9 10 "github.com/hashicorp/logutils" 11 ) 12 13 // These are the environmental variables that determine if we log, and if 14 // we log whether or not the log should go to a file. 15 const ( 16 EnvLog = "TF_LOG" // Set to True 17 EnvLogFile = "TF_LOG_PATH" // Set to a file 18 ) 19 20 var validLevels = []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"} 21 22 // LogOutput determines where we should send logs (if anywhere) and the log level. 23 func LogOutput() (logOutput io.Writer, err error) { 24 logOutput = ioutil.Discard 25 envLevel := os.Getenv(EnvLog) 26 if envLevel == "" { 27 return 28 } 29 30 logOutput = os.Stderr 31 if logPath := os.Getenv(EnvLogFile); logPath != "" { 32 var err error 33 logOutput, err = os.Create(logPath) 34 if err != nil { 35 return nil, err 36 } 37 } 38 39 // This was the default since the beginning 40 logLevel := logutils.LogLevel("TRACE") 41 42 if isValidLogLevel(envLevel) { 43 // allow following for better ux: info, Info or INFO 44 logLevel = logutils.LogLevel(strings.ToUpper(envLevel)) 45 } else { 46 log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v", 47 envLevel, validLevels) 48 } 49 50 logOutput = &logutils.LevelFilter{ 51 Levels: validLevels, 52 MinLevel: logLevel, 53 Writer: logOutput, 54 } 55 56 return 57 } 58 59 func isValidLogLevel(level string) bool { 60 for _, l := range validLevels { 61 if strings.ToUpper(level) == string(l) { 62 return true 63 } 64 } 65 66 return false 67 }