Open dnephin opened 1 year ago
One option seems to be a new method on Logger
:
type logWriter struct {
logger Logger
level Level
}
func (w logWriter) Write(p []byte) (n int, err error) {
n = len(p)
p = trimTrailingNewline(p)
w.logger.WithLevel(w.level).CallerSkipFrame(1).Msg(string(p))
return n, nil
}
func (l Logger) LogWriter(level Level) io.Writer {
return logWriter{level: level, logger: l}
}
You could just try to do logger.With().Str("level", "warn").Logger()
? Untested, but maybe it would work?
I thought that one way to solve this would be to have a writer which would map missing level to a level you would need, but I realized that it is not really possible to map level inside a writer because you would also have to change level
field inside the JSON payload so you would have to parse/marshal JSON again. Level mapping should be done at some other level it seems.
If you implement the LevelWriter
interface, you will get the level for each log line.
Yes, that was my initial thought, but it is still hard to modify the line itself, you have to unparse it, set manually level
field in it to the new level, and marshal it back.
Ah yes, the writer is not the right place for rewriting events, it is too late.
I've been using https://pkg.go.dev/github.com/rs/zerolog#Logger.Write to emit error logs from https://pkg.go.dev/net/http#Server and as the stderr for https://pkg.go.dev/os/exec#Cmd, so that output all goes to the same place.
In both of those cases the
level
of the log messages is alwaysnil
, which I guess makes sense because nothing is setting the level.Is there some way to set a default level for
Logger.Write
? Any suggestions for how I might be able to set a level on these log lines? Thanks!