github.com/andresvia/terraform@v0.6.15-0.20160412045437-d51c75946785/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  
    26  	logLevel := LogLevel()
    27  	if logLevel == "" {
    28  		return
    29  	}
    30  
    31  	logOutput = os.Stderr
    32  	if logPath := os.Getenv(EnvLogFile); logPath != "" {
    33  		var err error
    34  		logOutput, err = os.Create(logPath)
    35  		if err != nil {
    36  			return nil, err
    37  		}
    38  	}
    39  
    40  	// This was the default since the beginning
    41  	logOutput = &logutils.LevelFilter{
    42  		Levels:   validLevels,
    43  		MinLevel: logutils.LogLevel(logLevel),
    44  		Writer:   logOutput,
    45  	}
    46  
    47  	return
    48  }
    49  
    50  // LogLevel returns the current log level string based the environment vars
    51  func LogLevel() string {
    52  	envLevel := os.Getenv(EnvLog)
    53  	if envLevel == "" {
    54  		return ""
    55  	}
    56  
    57  	logLevel := "TRACE"
    58  	if isValidLogLevel(envLevel) {
    59  		// allow following for better ux: info, Info or INFO
    60  		logLevel = strings.ToUpper(envLevel)
    61  	} else {
    62  		log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v",
    63  			envLevel, validLevels)
    64  	}
    65  
    66  	return logLevel
    67  }
    68  
    69  // IsDebugOrHigher returns whether or not the current log level is debug or trace
    70  func IsDebugOrHigher() bool {
    71  	level := string(LogLevel())
    72  	return level == "DEBUG" || level == "TRACE"
    73  }
    74  
    75  func isValidLogLevel(level string) bool {
    76  	for _, l := range validLevels {
    77  		if strings.ToUpper(level) == string(l) {
    78  			return true
    79  		}
    80  	}
    81  
    82  	return false
    83  }