zerolog icon indicating copy to clipboard operation
zerolog copied to clipboard

Output from Logger.Write always has a nil level

Open dnephin opened this issue 3 years ago • 6 comments

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 always nil, 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!

dnephin avatar Dec 05 '22 20:12 dnephin

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}
}

dnephin avatar Jan 20 '23 23:01 dnephin

You could just try to do logger.With().Str("level", "warn").Logger()? Untested, but maybe it would work?

mitar avatar Aug 18 '23 13:08 mitar

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.

mitar avatar Aug 22 '23 10:08 mitar

If you implement the LevelWriter interface, you will get the level for each log line.

rs avatar Aug 22 '23 10:08 rs

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.

mitar avatar Aug 22 '23 11:08 mitar

Ah yes, the writer is not the right place for rewriting events, it is too late.

rs avatar Aug 22 '23 11:08 rs