zerolog使用stdout和文件记录器时,在文件中添加了额外的消息字段。

huangapple go评论99阅读模式
英文:

zerolog with stdout and file logger adds additional message field in the file

问题

我正在使用zerolog包在我的Go项目中,并且我需要将内容同时记录到文件和stdout中。我参考了这里的内容。我唯一做的更改是,我直接影响全局日志记录器,而不是创建一个名为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!")

它会在stdout中产生以下输出,这是预期的。

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

但是,文件内容变得混乱,有一个额外的message字段再次包装了上面的输出。

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

我该如何强制zerolog在记录内容时不添加额外的message字段?

英文:

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 ?

答案1

得分: 6

MultiLevelWriter接受io.Writer类型的参数。因此,你可以将runLogFile作为参数传递给它。

最终,代码看起来像这样:

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!")
英文:

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!")

huangapple
  • 本文由 发表于 2022年9月15日 20:15:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/73730972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定