英文:
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!")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论