forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
66 lines (54 loc) · 1.4 KB
/
log.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"io"
"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 = nil
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
}