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

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

Open
dnephin opened this issue Dec 5, 2022 · 6 comments
Open

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

dnephin opened this issue Dec 5, 2022 · 6 comments

Comments

@dnephin
Copy link

dnephin commented Dec 5, 2022

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
Copy link
Author

dnephin commented Jan 20, 2023

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
Copy link
Contributor

mitar commented Aug 18, 2023

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

@mitar
Copy link
Contributor

mitar commented Aug 22, 2023

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
Copy link
Owner

rs commented Aug 22, 2023

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

@mitar
Copy link
Contributor

mitar commented Aug 22, 2023

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
Copy link
Owner

rs commented Aug 22, 2023

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

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

3 participants