From e0a4c37fc172f3f307d7b814b5bb9a20c74385fc Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Tue, 4 Feb 2020 21:47:15 +0200 Subject: [PATCH] lib/logger: add `-loggerOutput` command-line flag This flag allows changing log output from `stderr` to `stdout` if `-loggerOutput=stdout` is set. Updates https://github.com/VictoriaMetrics/VictoriaMetrics/issues/306 --- lib/logger/logger.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/logger/logger.go b/lib/logger/logger.go index 403228016..b2a29a720 100644 --- a/lib/logger/logger.go +++ b/lib/logger/logger.go @@ -4,6 +4,7 @@ import ( "errors" "flag" "fmt" + "io" "log" "os" "runtime" @@ -19,6 +20,7 @@ import ( var ( loggerLevel = flag.String("loggerLevel", "INFO", "Minimum level of errors to log. Possible values: INFO, ERROR, FATAL, PANIC") loggerFormat = flag.String("loggerFormat", "default", "Format for logs. Possible values: default, json") + loggerOutput = flag.String("loggerOutput", "stderr", "Output for the logs. Supported values: stderr, stdout") ) // Init initializes the logger. @@ -27,12 +29,26 @@ var ( // // There is no need in calling Init from tests. func Init() { + setLoggerOutput() validateLoggerLevel() validateLoggerFormat() go errorsLoggedCleaner() logAllFlags() } +func setLoggerOutput() { + switch *loggerOutput { + case "stderr": + output = os.Stderr + case "stdout": + output = os.Stdout + default: + panic(fmt.Errorf("FATAL: unsupported `loggerOutput` value: %q; supported values are: stderr, stdout", *loggerOutput)) + } +} + +var output io.Writer + func validateLoggerLevel() { switch *loggerLevel { case "INFO", "ERROR", "FATAL", "PANIC": @@ -145,7 +161,7 @@ func logMessage(level, msg string, skipframes int) { // Serialize writes to log. mu.Lock() - fmt.Fprint(os.Stderr, logMsg) + fmt.Fprint(output, logMsg) mu.Unlock() // Increment vm_log_messages_total