Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Anyway to have errors/warnings go to stderr and info/debug to stdout #363

Open
gemscoder opened this issue Sep 22, 2021 · 5 comments
Open

Comments

@gemscoder
Copy link

Hi,
Is it possible for zerolog to log errors/warnings to stderr and everything else to stdout or do I need to use 2 different loggers ?I am using kubernetes environment thank for you help in advance.

@rs
Copy link
Owner

rs commented Sep 22, 2021

You can implement a zerolog.LevelWriter that would use the level to choose between os.Stdout and os.Stderr.

@gemscoder
Copy link
Author

Thanks for your reply. That helps. Any sample code?

@rs
Copy link
Owner

rs commented Sep 22, 2021

You can find some example in the writer.go file.

@mitar
Copy link
Contributor

mitar commented Aug 11, 2023

This has also been discussed here.

@v613
Copy link

v613 commented Dec 22, 2023

@gemscoder here is my little contribution.

package main

import (
	"io"
	"os"

	"github.com/rs/zerolog"
)

type myWriter struct {
	io.Writer
	ErrOut io.Writer
}

func (mw myWriter) WriteLevel(lvl zerolog.Level, txt []byte) (int, error) {
	if lvl > zerolog.InfoLevel {
		// return os.Stderr.Write(txt)
		return mw.ErrOut.Write(txt)
	}
	return mw.Writer.Write(txt)
}

func main() {
	out := myWriter{os.Stdout, os.Stderr}
	l := zerolog.New(out)
	l.Info().Msg("to standard out")
	l.Error().Msg("to standard error")
}
go run main.go 2> >(sed 's/^/stderr: /') > >(sed 's/^/stdout: /')
stdout: {"level":"info","message":"to standard out"}
stderr: {"level":"error","message":"to standard error"}
$ go run main.go 2> err.log
{"level":"info","message":"to standard out"}
$ cat err.log 
{"level":"error","message":"to standard error"}
$

We could probably close this issue, especially since it's from 2021.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants