在Golang中测试日志语句的输出

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

Testing a Log statement output in Golang

问题

你好,我想确认一下Log.error()的输出是否有效,我有以下的代码:

func logError(param bool) bool {
    if param == true {
        log.Error(fmt.Sprintf("我需要以某种方式测试这里的输出是否正确"))
    }
    return param
}

我不被允许修改现有的代码,我只想确保由我的logError函数打印到控制台的内容与我期望的一致。

在不修改现有代码的情况下,是否有可能实现这一点呢?谢谢。

英文:

Hi I want to check that the output of a Log.error() is valid, I have this following code here

func logError(param bool)
bool {
    if (param == true)
        log.Error(fmt.Sprintf("I need to somehow tst, that the output here is correct"))

    return param;
}

I am not allowed to modify my existing code, I just want to ensure that whatever is printed by the console by my logError function, is what I expect it to be.

Is this possible without modifying my existing code, thank you.

答案1

得分: 2

使用logrus,你可以在测试中捕获日志记录器的输出:

oldOut := log.StandardLogger().Out // 保存当前的日志目标
buf := bytes.Buffer{}
log.SetOutput(&buf)
logError(true)
// 在这里,buf.String() 应该给你日志消息
log.SetOutput(oldOut) // 恢复日志目标
英文:

With logrus, you can capture the output of the logger in a test:

oldOut:=log.StandardLogger().Out // Save current log target
buf:=bytes.Buffer{}
log.SetOutput(&buf)
logError(true)
// Here, buf.String() should give you the log msg
log.SetOutput(oldOut) // Restore log target

huangapple
  • 本文由 发表于 2021年10月26日 10:14:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/69716723.html
匿名

发表评论

匿名网友

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

确定