Javedullah Ahmadi
Javedullah Ahmadi

Reputation: 61

Testing a Log statement output in Golang

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.

Upvotes: 3

Views: 3925

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51467

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

Upvotes: 3

Related Questions