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
This commit is contained in:
Aliaksandr Valialkin 2020-02-04 21:47:15 +02:00
parent 7f3e3a6034
commit e0a4c37fc1

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"flag" "flag"
"fmt" "fmt"
"io"
"log" "log"
"os" "os"
"runtime" "runtime"
@ -19,6 +20,7 @@ import (
var ( var (
loggerLevel = flag.String("loggerLevel", "INFO", "Minimum level of errors to log. Possible values: INFO, ERROR, FATAL, PANIC") 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") 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. // Init initializes the logger.
@ -27,12 +29,26 @@ var (
// //
// There is no need in calling Init from tests. // There is no need in calling Init from tests.
func Init() { func Init() {
setLoggerOutput()
validateLoggerLevel() validateLoggerLevel()
validateLoggerFormat() validateLoggerFormat()
go errorsLoggedCleaner() go errorsLoggedCleaner()
logAllFlags() 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() { func validateLoggerLevel() {
switch *loggerLevel { switch *loggerLevel {
case "INFO", "ERROR", "FATAL", "PANIC": case "INFO", "ERROR", "FATAL", "PANIC":
@ -145,7 +161,7 @@ func logMessage(level, msg string, skipframes int) {
// Serialize writes to log. // Serialize writes to log.
mu.Lock() mu.Lock()
fmt.Fprint(os.Stderr, logMsg) fmt.Fprint(output, logMsg)
mu.Unlock() mu.Unlock()
// Increment vm_log_messages_total // Increment vm_log_messages_total