rs / zerolog

Zero Allocation JSON Logger
MIT License
10.41k stars 567 forks source link

Output from Logger.Write always has a nil level #508

Open dnephin opened 1 year ago

dnephin commented 1 year ago

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 commented 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}
}
mitar commented 1 year ago

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

mitar commented 1 year ago

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.

rs commented 1 year ago

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

mitar commented 1 year ago

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.

rs commented 1 year ago

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