Clean up some of the log path detection code

/cc @markpeek I think this is much cleaner. Also, I made it so it
doesn't append by default... I like the idea of appending but it scares
me that for a bug report someone might put like a multi-megabyte gist of
logs at me. HAHA. We'll see.
This commit is contained in:
Mitchell Hashimoto 2013-07-14 11:00:44 +09:00
parent 097e44da48
commit 8e79bb44a7
2 changed files with 18 additions and 14 deletions

View File

@ -10,6 +10,8 @@ FEATURES:
floppy disks when booting. This allows for unattended Windows installs. floppy disks when booting. This allows for unattended Windows installs.
* `packer build` has a new `-force` flag that forces the removal of * `packer build` has a new `-force` flag that forces the removal of
existing artifacts if they exist. [GH-173] existing artifacts if they exist. [GH-173]
* You can now log to a file (instead of just stderr) by setting the
`PACKER_LOG_FILE` environmental variable. [GH-168]
IMPROVEMENTS: IMPROVEMENTS:

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"github.com/mitchellh/packer/packer" "github.com/mitchellh/packer/packer"
"github.com/mitchellh/packer/packer/plugin" "github.com/mitchellh/packer/packer/plugin"
"io"
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
@ -16,24 +17,25 @@ import (
func main() { func main() {
// Setup logging if PACKER_LOG is set. // Setup logging if PACKER_LOG is set.
// Log to PACKER_LOG_PATH if it is set, otherwise default to stderr. // Log to PACKER_LOG_PATH if it is set, otherwise default to stderr.
if os.Getenv("PACKER_LOG") == "" { var logOutput io.Writer = ioutil.Discard
// If we don't have logging explicitly enabled, then disable it if os.Getenv("PACKER_LOG") != "" {
log.SetOutput(ioutil.Discard) logOutput = os.Stderr
} else {
if log_path := os.Getenv("PACKER_LOG_PATH"); log_path == "" { if logPath := os.Getenv("PACKER_LOG_PATH"); logPath != "" {
log.SetOutput(os.Stderr) var err error
} else { logOutput, err = os.Create(logPath)
file, err := os.OpenFile(log_path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600) if err != nil {
if err == nil { fmt.Fprintf(
log.SetOutput(file) os.Stderr,
} else { "Couldn't open '%s' for logging: %s",
// Problem opening the file, fail back to Stderr logPath, err)
log.SetOutput(os.Stderr) os.Exit(1)
log.Printf("Could not open %s for logging (%s). Using stderr instead.", log_path, err.Error())
} }
} }
} }
log.SetOutput(logOutput)
// If there is no explicit number of Go threads to use, then set it // If there is no explicit number of Go threads to use, then set it
if os.Getenv("GOMAXPROCS") == "" { if os.Getenv("GOMAXPROCS") == "" {
runtime.GOMAXPROCS(runtime.NumCPU()) runtime.GOMAXPROCS(runtime.NumCPU())