英文:
How to store output of logrus to some variable?
问题
这是将输入值转换为JSON格式的代码。它显示了正确的输出,但我想将该输出存储并使用fmt.Printf
返回。
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.SetFormatter(&log.JSONFormatter{})
standardFields := log.Fields{
"Number of threads": "1",
"Odd number": "3",
}
log.WithFields(standardFields).Info("Golang")
}
这段代码使用了logrus库来记录日志,并将日志格式设置为JSON格式。然后,创建了一个包含标准字段的map,其中包括"Number of threads"和"Odd number"两个字段。最后,使用logrus的WithFields方法将标准字段添加到日志中,并使用Info方法记录日志信息为"Golang"。
英文:
This is code that converts the entered value to JSON format. It shows the correct output but I want to store that output and return it using fmt.Printf
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.SetFormatter(&log.JSONFormatter{})
standardFields := log.Fields{
"Number of threads": "1",
"Odd number": "3",
}
log.WithFields(standardFields).Info("Golang")
}
答案1
得分: 1
当你使用logrus.New()
创建一个新的日志记录器时,你可以提供Out
字段来指向任何你希望的io.Writer
。这是关于该字段的文档:
type Logger struct {
// 日志会在互斥锁中被`io.Copy`到这里。通常将其设置为一个文件,或者保持默认值`os.Stderr`。你也可以将其设置为更复杂的东西,比如将日志记录到Kafka。
Out io.Writer
...
...
}
例如,你可以创建一个新的bytes.Buffer
并将其设置为Out
字段。这类似于“将日志记录到变量”。
类似地,你可以使用SetOutput
函数设置默认日志记录器的输出。
英文:
When you create a new logger with logrus.New(), you can provide the Out
field to point to any io.Writer
you wish. Here's the documentation for this field:
type Logger struct {
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
// file, or leave it default which is `os.Stderr`. You can also set this to
// something more adventurous, such as logging to Kafka.
Out io.Writer
...
...
So, for example you could create a new bytes.Buffer and set that as the Out
field. This is akin to "logging to a variable".
Similarly, you can set the output of the default logger with the SetOutput function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论