opentofu/helper/logging/logging.go
Paul Hinze 4bd4e18def core: use same logging setup for acctests
We weren't doing any log setup for acceptance tests, which made it
difficult to wrangle log output in CI.

This moves the log setup functions we use in `main` over into a helper
package so we can use them for acceptance tests as well.

This means that acceptance tests will by default be a _lot_ quieter,
only printing out actual test output. Setting `TF_LOG=trace` will
restore the full prior noise level.

Only minor behavior change is to make `ioutil.Discard` the default
return value rather than a `nil` that needs to be checked for.
2015-12-08 17:50:36 -06:00

68 lines
1.4 KiB
Go

package logging
import (
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/hashicorp/logutils"
)
// These are the environmental variables that determine if we log, and if
// we log whether or not the log should go to a file.
const (
EnvLog = "TF_LOG" // Set to True
EnvLogFile = "TF_LOG_PATH" // Set to a file
)
var validLevels = []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"}
// LogOutput determines where we should send logs (if anywhere) and the log level.
func LogOutput() (logOutput io.Writer, err error) {
logOutput = ioutil.Discard
envLevel := os.Getenv(EnvLog)
if envLevel == "" {
return
}
logOutput = os.Stderr
if logPath := os.Getenv(EnvLogFile); logPath != "" {
var err error
logOutput, err = os.Create(logPath)
if err != nil {
return nil, err
}
}
// This was the default since the beginning
logLevel := logutils.LogLevel("TRACE")
if isValidLogLevel(envLevel) {
// allow following for better ux: info, Info or INFO
logLevel = logutils.LogLevel(strings.ToUpper(envLevel))
} else {
log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v",
envLevel, validLevels)
}
logOutput = &logutils.LevelFilter{
Levels: validLevels,
MinLevel: logLevel,
Writer: logOutput,
}
return
}
func isValidLogLevel(level string) bool {
for _, l := range validLevels {
if strings.ToUpper(level) == string(l) {
return true
}
}
return false
}