【问题标题】:Testing a Log statement output in Golang在 Golang 中测试日志语句输出
【发布时间】:2021-12-11 10:48:15
【问题描述】:

您好,我想检查 Log.error() 的输出是否有效,我这里有以下代码

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;
}

我不允许修改我现有的代码,我只想确保控制台通过我的 logError 函数打印的任何内容都是我所期望的。

是否可以不修改我现有的代码,谢谢。

【问题讨论】:

  • 答案取决于您使用的日志库。
  • 抱歉,我刚刚添加了我的日志库。
  • 我使用的日志库是github.com/sirupsen/logrus

标签: go testing logging


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-12-16
    • 2018-12-06
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2022-07-06
    • 2018-05-29
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多