diff --git a/daemon/log/log.go b/daemon/log/log.go index 96b09511d5..3379781c5f 100644 --- a/daemon/log/log.go +++ b/daemon/log/log.go @@ -46,6 +46,7 @@ const ( var ( WithColors = true Output = os.Stdout + StdoutFile = "/dev/stdout" DateFormat = "2006-01-02 15:04:05" MinLevel = INFO @@ -115,8 +116,8 @@ func Raw(format string, args ...interface{}) { // SetLogLevel sets the log level func SetLogLevel(newLevel int) { - mutex.RLock() - defer mutex.RUnlock() + mutex.Lock() + defer mutex.Unlock() MinLevel = newLevel } @@ -142,21 +143,35 @@ func Log(level int, format string, args ...interface{}) { } func setDefaultLogOutput() { + mutex.Lock() Output = os.Stdout + mutex.Unlock() } -// OpenFile opens a file the print out the logs +// OpenFile opens a file to print out the logs func OpenFile(logFile string) (err error) { - mutex.Lock() - defer mutex.Unlock() + if logFile == StdoutFile { + setDefaultLogOutput() + return + } if Output, err = os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err != nil { + Error("Error opening log: ", logFile, err) + //fallback to stdout setDefaultLogOutput() } + Important("Start writing logs to ", logFile) return err } +// Close closes the current output file descriptor +func Close() { + if Output != os.Stdout { + Output.Close() + } +} + // Debug is the log level for debugging purposes func Debug(format string, args ...interface{}) { Log(DEBUG, format, args...) diff --git a/daemon/main.go b/daemon/main.go index 15d81343a3..8d47e005d5 100644 --- a/daemon/main.go +++ b/daemon/main.go @@ -65,8 +65,8 @@ func init() { flag.BoolVar(&noLiveReload, "no-live-reload", debug, "Disable rules live reloading.") flag.StringVar(&logFile, "log-file", logFile, "Write logs to this file instead of the standard output.") - flag.BoolVar(&debug, "debug", debug, "Enable debug logs.") - flag.BoolVar(&warning, "warning", warning, "Enable warning logs.") + flag.BoolVar(&debug, "debug", debug, "Enable debug level logs.") + flag.BoolVar(&warning, "warning", warning, "Enable warning level logs.") flag.BoolVar(&important, "important", important, "Enable important level logs.") flag.BoolVar(&errorlog, "error", errorlog, "Enable error level logs.") @@ -74,6 +74,10 @@ func init() { flag.StringVar(&memProfile, "mem-profile", memProfile, "Write memory profile to this file.") } +func overwriteLogging() bool { + return debug || warning || important || errorlog || logFile != "" +} + func setupLogging() { golog.SetOutput(ioutil.Discard) if debug { @@ -89,6 +93,7 @@ func setupLogging() { } if logFile != "" { + log.Close() if err := log.OpenFile(logFile); err != nil { log.Error("Error opening user defined log: ", logFile, err) } @@ -325,6 +330,9 @@ func main() { pktChan = queue.Packets() uiClient = ui.NewClient(uiSocket, stats, rules) + if overwriteLogging() { + setupLogging() + } // overwrite monitor method from configuration if the user has passed // the option via command line. if procmonMethod != "" {