我想使用 go kit 中的记录器存储库,我看到了
作者还提供了 logrus API/factory ,同时尝试使用 logrus 的一些常见 API 功能进行测试,例如 ,withFields
和 error
/info
/panic
等
我不能使用它们只能记录
知道如何添加缺少的日志功能吗?
logrus.WithField API。
这就是我想念的
log.WithFields(log.Fields{
"animal": "walrus",
}).Info("A walrus appears")
还有信息/错误/调试等
这是我尝试过的
package main
import (
log "github.com/go-kit/kit/log/logrus"
"github.com/sirupsen/logrus"
)
func main() {
logrusLogger := logrus.New()
logrusLogger.Formatter = &logrus.JSONFormatter{TimestampFormat: "02-01-2006 15:04:05"}
logger := log.NewLogrusLogger(logrusLogger)
logger.Log("hello", "world”) //working
logger.WithFields( //doesnt work
logger.Info( //doesnt work
}
记录器的类型为logrus
,但我不能使用withFields
或info/error/debug等,知道我在这里错过了什么吗?
当日志工具包创建一些工厂时,有没有办法使用 logrus api ?
最佳答案
这是因为 log.NewLogrusLogger()
创建了未导出的 logruslogger
,它只有一个方法 Log
(满足 log.Logger
接口(interface))。它不支持 logrus 本身的其他方法。
此Log
方法可以在记录时采用键值对中的参数并将它们放入logrus.Fields
中。因此,如果您执行 Log("hello", "world")
,它会将 hello
字段的值设置为 world
。但这不适用于 level
或其他功能。
但是,由于 logrus.FieldLogger
嵌入在 logruslogger
的实现中,我们可以断言我们的记录器的行为类似于 logrus.FieldLogger
然后执行以下操作:
package main
import (
log "github.com/go-kit/kit/log/logrus"
"github.com/sirupsen/logrus"
)
func main() {
logrusLogger := logrus.New()
logrusLogger.Formatter = &logrus.JSONFormatter{TimestampFormat: "02-01-2006 15:04:05"}
logger := log.NewLogrusLogger(logrusLogger).(logrus.FieldLogger)
logger.Error("Hello")
logger.Warn("Warning you")
logger.WithField("good", "bad").Infoln("is it good or bad?")
}
我希望这有帮助。但由于他们只公开了 Log 方法,因此这些方法背后可能存在有意识的设计决策。您可以继续仅使用 Log
或者如果您想要更大的灵 active ,我建议您设置自己的记录器(使用 logrus),而不是我上面所做的。在我看来,这将是一种更清洁的方法。
关于go - 使用 go-kit logger api 缺少的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257555/