use hclog as the default logger

Inject hclog as the default logger in the main binary.
This commit is contained in:
James Bardin 2020-10-17 09:38:18 -04:00
parent 776482cc59
commit 211edf5d75
4 changed files with 37 additions and 43 deletions

View File

@ -1,12 +1,15 @@
package logging package logging
import ( import (
"fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
"strings" "strings"
"syscall" "syscall"
"github.com/hashicorp/go-hclog"
) )
// These are the environmental variables that determine if we log, and if // These are the environmental variables that determine if we log, and if
@ -19,39 +22,38 @@ const (
// ValidLevels are the log level names that Terraform recognizes. // ValidLevels are the log level names that Terraform recognizes.
var ValidLevels = []LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"} var ValidLevels = []LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"}
// LogOutput determines where we should send logs (if anywhere) and the log level. // logger is the global hclog logger
func LogOutput() (logOutput io.Writer, err error) { var logger hclog.Logger
logOutput = ioutil.Discard
func init() {
logOutput := io.Writer(os.Stderr)
logLevel := CurrentLogLevel() logLevel := CurrentLogLevel()
if logLevel == "" { if logLevel == "" {
return logOutput = ioutil.Discard
} }
logOutput = os.Stderr
if logPath := os.Getenv(EnvLogFile); logPath != "" { if logPath := os.Getenv(EnvLogFile); logPath != "" {
var err error f, err := os.OpenFile(logPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_APPEND, 0666)
logOutput, err = os.OpenFile(logPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_APPEND, 0666)
if err != nil { if err != nil {
return nil, err fmt.Fprintf(os.Stderr, "Error opening log file: %v\n", err)
} else {
logOutput = f
} }
} }
if logLevel == "TRACE" { logger = hclog.New(&hclog.LoggerOptions{
// Just pass through logs directly then, without any level filtering at all. Level: hclog.LevelFromString(logLevel),
return logOutput, nil Output: logOutput,
})
} }
// Otherwise we'll use our level filter, which is a heuristic-based // LogOutput determines where we should send logs (if anywhere) and the log level.
// best effort thing that is not totally reliable but helps to reduce func LogOutput() (logOutput io.Writer, err error) {
// the volume of logs in some cases. return logger.StandardWriter(&hclog.StandardLoggerOptions{InferLevels: true}), nil
logOutput = &LevelFilter{
Levels: ValidLevels,
MinLevel: LogLevel(logLevel),
Writer: logOutput,
} }
return logOutput, nil func HCLogger() hclog.Logger {
return logger
} }
// SetOutput checks for a log destination with LogOutput, and calls // SetOutput checks for a log destination with LogOutput, and calls
@ -67,20 +69,22 @@ func SetOutput() {
out = ioutil.Discard out = ioutil.Discard
} }
// the hclog logger will add the prefix info
log.SetFlags(0)
log.SetPrefix("")
log.SetOutput(out) log.SetOutput(out)
} }
// CurrentLogLevel returns the current log level string based the environment vars // CurrentLogLevel returns the current log level string based the environment vars
func CurrentLogLevel() string { func CurrentLogLevel() string {
envLevel := os.Getenv(EnvLog) envLevel := strings.ToUpper(os.Getenv(EnvLog))
if envLevel == "" { if envLevel == "" {
return "" return ""
} }
logLevel := "TRACE" logLevel := "TRACE"
if isValidLogLevel(envLevel) { if isValidLogLevel(envLevel) {
// allow following for better ux: info, Info or INFO logLevel = envLevel
logLevel = strings.ToUpper(envLevel)
} else { } else {
log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v", log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v",
envLevel, ValidLevels) envLevel, ValidLevels)
@ -100,7 +104,7 @@ func IsDebugOrHigher() bool {
func isValidLogLevel(level string) bool { func isValidLogLevel(level string) bool {
for _, l := range ValidLevels { for _, l := range ValidLevels {
if strings.ToUpper(level) == string(l) { if level == string(l) {
return true return true
} }
} }

13
main.go
View File

@ -19,7 +19,6 @@ import (
"github.com/hashicorp/terraform/command/cliconfig" "github.com/hashicorp/terraform/command/cliconfig"
"github.com/hashicorp/terraform/command/format" "github.com/hashicorp/terraform/command/format"
"github.com/hashicorp/terraform/httpclient" "github.com/hashicorp/terraform/httpclient"
"github.com/hashicorp/terraform/internal/logging"
"github.com/hashicorp/terraform/version" "github.com/hashicorp/terraform/version"
"github.com/mattn/go-colorable" "github.com/mattn/go-colorable"
"github.com/mattn/go-shellwords" "github.com/mattn/go-shellwords"
@ -37,8 +36,6 @@ const (
) )
func main() { func main() {
// Override global prefix set by go-dynect during init()
log.SetPrefix("")
os.Exit(realMain()) os.Exit(realMain())
} }
@ -51,13 +48,6 @@ func realMain() int {
} }
if !panicwrap.Wrapped(&wrapConfig) { if !panicwrap.Wrapped(&wrapConfig) {
// Determine where logs should go in general (requested by the user)
logWriter, err := logging.LogOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't setup log output: %s", err)
return 1
}
// We always send logs to a temporary file that we use in case // We always send logs to a temporary file that we use in case
// there is a panic. Otherwise, we delete it. // there is a panic. Otherwise, we delete it.
logTempFile, err := ioutil.TempFile("", "terraform-log") logTempFile, err := ioutil.TempFile("", "terraform-log")
@ -76,7 +66,7 @@ func realMain() int {
// Create the configuration for panicwrap and wrap our executable // Create the configuration for panicwrap and wrap our executable
wrapConfig.Handler = panicHandler(logTempFile) wrapConfig.Handler = panicHandler(logTempFile)
wrapConfig.Writer = io.MultiWriter(logTempFile, logWriter) wrapConfig.Writer = os.Stderr
wrapConfig.Stdout = outW wrapConfig.Stdout = outW
wrapConfig.IgnoreSignals = ignoreSignals wrapConfig.IgnoreSignals = ignoreSignals
wrapConfig.ForwardSignals = forwardSignals wrapConfig.ForwardSignals = forwardSignals
@ -122,7 +112,6 @@ func init() {
func wrappedMain() int { func wrappedMain() int {
var err error var err error
log.SetOutput(os.Stderr)
log.Printf( log.Printf(
"[INFO] Terraform version: %s %s %s", "[INFO] Terraform version: %s %s %s",
Version, VersionPrerelease, GitCommit) Version, VersionPrerelease, GitCommit)

View File

@ -4,8 +4,8 @@ import (
"os" "os"
"os/exec" "os/exec"
hclog "github.com/hashicorp/go-hclog"
plugin "github.com/hashicorp/go-plugin" plugin "github.com/hashicorp/go-plugin"
"github.com/hashicorp/terraform/internal/logging"
"github.com/hashicorp/terraform/plugin/discovery" "github.com/hashicorp/terraform/plugin/discovery"
) )
@ -17,11 +17,7 @@ var enableAutoMTLS = os.Getenv("TF_DISABLE_PLUGIN_TLS") == ""
// ClientConfig returns a configuration object that can be used to instantiate // ClientConfig returns a configuration object that can be used to instantiate
// a client for the plugin described by the given metadata. // a client for the plugin described by the given metadata.
func ClientConfig(m discovery.PluginMeta) *plugin.ClientConfig { func ClientConfig(m discovery.PluginMeta) *plugin.ClientConfig {
logger := hclog.New(&hclog.LoggerOptions{ logger := logging.HCLogger()
Name: "plugin",
Level: hclog.Trace,
Output: os.Stderr,
})
return &plugin.ClientConfig{ return &plugin.ClientConfig{
Cmd: exec.Command(m.Path), Cmd: exec.Command(m.Path),

View File

@ -10,6 +10,7 @@ import (
"github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/addrs"
"github.com/hashicorp/terraform/configs" "github.com/hashicorp/terraform/configs"
"github.com/hashicorp/terraform/instances" "github.com/hashicorp/terraform/instances"
"github.com/hashicorp/terraform/internal/logging"
"github.com/hashicorp/terraform/lang" "github.com/hashicorp/terraform/lang"
"github.com/hashicorp/terraform/plans" "github.com/hashicorp/terraform/plans"
"github.com/hashicorp/terraform/providers" "github.com/hashicorp/terraform/providers"
@ -20,6 +21,10 @@ import (
"github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty"
) )
func init() {
logging.SetOutput()
}
// InputMode defines what sort of input will be asked for when Input // InputMode defines what sort of input will be asked for when Input
// is called on Context. // is called on Context.
type InputMode byte type InputMode byte