如何将logrus的输出存储到某个变量中?

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

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.

huangapple
  • 本文由 发表于 2021年6月3日 18:14:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/67819563.html
匿名

发表评论

匿名网友

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

确定