component-base: use stderr as default output stream for JSON

This makes it consistent with klog's text output and avoids polluting the
programs normal output with log messages. This may become relevant for command
line tools like "kubectl".
This commit is contained in:
Patrick Ohly 2021-11-04 10:24:01 +01:00
parent 23df2b97f7
commit b4988a4259
2 changed files with 6 additions and 1 deletions

View File

@ -54,6 +54,8 @@ func NewLoggerCommand() *cobra.Command {
} }
func runLogger() { func runLogger() {
fmt.Println("This is normal output via stdout.")
fmt.Fprintln(os.Stderr, "This is other output via stderr.")
klog.Infof("Log using Infof, key: %s", "value") klog.Infof("Log using Infof, key: %s", "value")
klog.InfoS("Log using InfoS", "key", "value") klog.InfoS("Log using InfoS", "key", "value")
err := errors.New("fail") err := errors.New("fail")

View File

@ -93,6 +93,7 @@ var _ registry.LogFormatFactory = Factory{}
func (f Factory) Create(options config.FormatOptions) (logr.Logger, func()) { func (f Factory) Create(options config.FormatOptions) (logr.Logger, func()) {
if options.JSON.SplitStream { if options.JSON.SplitStream {
// stdout for info messages, stderr for errors.
infoStream := zapcore.Lock(os.Stdout) infoStream := zapcore.Lock(os.Stdout)
size := options.JSON.InfoBufferSize.Value() size := options.JSON.InfoBufferSize.Value()
if size > 0 { if size > 0 {
@ -107,7 +108,9 @@ func (f Factory) Create(options config.FormatOptions) (logr.Logger, func()) {
} }
return NewJSONLogger(infoStream, zapcore.Lock(os.Stderr)) return NewJSONLogger(infoStream, zapcore.Lock(os.Stderr))
} }
out := zapcore.Lock(os.Stdout) // The default is to write to stderr (same as in klog's text output,
// doesn't get mixed with normal program output).
out := zapcore.Lock(os.Stderr)
return NewJSONLogger(out, out) return NewJSONLogger(out, out)
} }