log: simplify the logOutput function

The logOutput function had a bunch of nested checks in the code for the
function, as well as one ineffasign pointed out by golangci-lint.

This commit changes how special cases are processed, and changes a bit
how log redirection to a file is handled.
Prior to this commit, only when PACKER_LOG and PACKER_LOG_FILE are set
does Packer redirect logs to the specified path, which is a bit
superfluous as setting PACKER_LOG_FILE should be enough on its own to
redirect logs and enable verbose logs.

Now, when neither is set, no logOutput is set, if PACKER_LOG_FILE is set
(regardless of PACKER_LOG), we redirect to the specified file, and
finally if PACKER_LOG is set, we redirect to stderr.
pull/13110/head
Lucas Bajolet 2 years ago
parent 4436346fcb
commit 50850ef91b

@ -19,42 +19,46 @@ const EnvLogFile = "PACKER_LOG_PATH" //Set to a file
// logOutput determines where we should send logs (if anywhere).
func logOutput() (logOutput io.Writer, err error) {
logOutput = nil
if os.Getenv(EnvLog) != "" && os.Getenv(EnvLog) != "0" {
logOutput = os.Stderr
if logPath := os.Getenv(EnvLogFile); logPath != "" {
var err error
logOutput, err = os.Create(logPath)
if err != nil {
return nil, err
}
if logPath := os.Getenv(EnvLogFile); logPath != "" {
var err error
logOutput, err = os.Create(logPath)
if err != nil {
return nil, err
}
} else {
// no path; do a little light filtering to avoid double-dipping UI
// calls.
r, w := io.Pipe()
scanner := bufio.NewScanner(r)
scanner.Split(ScanLinesSmallerThanBuffer)
return logOutput, nil
}
go func(scanner *bufio.Scanner) {
for scanner.Scan() {
if strings.Contains(scanner.Text(), "ui:") {
continue
}
if strings.Contains(scanner.Text(), "ui error:") {
continue
}
os.Stderr.WriteString(fmt.Sprint(scanner.Text() + "\n"))
}
if err := scanner.Err(); err != nil {
os.Stderr.WriteString(err.Error())
w.Close()
}
}(scanner)
logOutput = w
}
// If we don't output logs to a file, or it wasn't requested, we can
// return immediately without setting an output for logs.
if os.Getenv(EnvLog) == "" || os.Getenv(EnvLog) == "0" {
return
}
// no path; do a little light filtering to avoid double-dipping UI
// calls.
r, w := io.Pipe()
scanner := bufio.NewScanner(r)
scanner.Split(ScanLinesSmallerThanBuffer)
go func(scanner *bufio.Scanner) {
defer w.Close()
for scanner.Scan() {
if strings.Contains(scanner.Text(), "ui:") {
continue
}
if strings.Contains(scanner.Text(), "ui error:") {
continue
}
fmt.Fprintf(os.Stderr, scanner.Text()+"\n")
}
if err := scanner.Err(); err != nil {
fmt.Fprintf(os.Stderr, "log output filter failed: %s\n", err)
}
}(scanner)
logOutput = w
return
}

Loading…
Cancel
Save