Home > Back-end >  zerolog with stdout and file logger adds additional message field in the file
zerolog with stdout and file logger adds additional message field in the file

Time:09-16

I am using zerolog package in my go project and I need to log the content in both file as well as stdout. I took reference from here. The only change I have made is, instead of creating new variable named logger, I am directly affecting the global logger.

runLogFile, _ := os.OpenFile(
        "myapp.log",
        os.O_APPEND|os.O_CREATE|os.O_WRONLY,
        0664,
    )
fileLogger := zerolog.New(runLogFile).With().Logger()
multi := zerolog.MultiLevelWriter(os.Stdout, fileLogger)
log.Logger = zerolog.New(multi).With().Timestamp().Logger()

log.Info().Msg("Hello World!")

It produces output in the stdout as shown below, which is expected.

{"level":"info","time":"2022-09-15T08:10:28-04:00","message":"Hello World!"}

But, the file content becomes messy with additional message field which wraps the above output again.

{"message":"{\"level\":\"info\",\"time\":\"2022-09-15T08:10:28-04:00\",\"message\":\"Hello World!\"}"}

How can I enforce the zerolog to log the content without additional message field ?

CodePudding user response:

MultiLevelWriter accept io.Writer. So you can input runLogFile to this.

In the end, the code look like this :

runLogFile, _ := os.OpenFile(
        "myapp.log",
        os.O_APPEND|os.O_CREATE|os.O_WRONLY,
        0664,
    )
multi := zerolog.MultiLevelWriter(os.Stdout, runLogFile)
log.Logger = zerolog.New(multi).With().Timestamp().Logger()

log.Info().Msg("Hello World!")
  • Related