如果不满足所需的级别,glog内容会被执行吗?

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

Will glog content been executed if does not meet required level

问题

问题很简单,我有一个像这样的日志:

glog.v(5).Infof("xxx %v", getLogContent())

但是我的 getLogContent() 是一个耗时的方法,所以我想问:当我的程序不满足 v(5) 级别时,getLogContent() 是否会被执行?

英文:

The question is simple, I have a log like this:

glog.v(5).Infof("xxx %v", getLogContent())

But my getLogContent() is a time consuming method, so I want to ask: will getLogContent() been executed or not when my program does not meet v(5) level?

答案1

得分: 2

是的。

如果你不希望getLogContent()被执行,你应该添加一个if语句。

if glog.V(5) {
    glog.V(5).Infof("xxx %v", getLogContent())
}

Go语言会评估所有的参数,所以getLogContent函数会被调用,但是如果未达到所需的详细程度,输出将不会被记录。

英文:

Yes.

You should add an if statement if you don't want getLogContent() to run

if glog.V(5) {
    glog.V(5).Infof("xxx %v", getLogContent())
}

Go evaluates all arguments, so getLogContent will get called but the output will not be logged if the verbosity level has not been met.

答案2

得分: 0

我对此很好奇并进行了一些尝试。我不知道这对你是否有用,但这很有趣。

通过使用lambda函数,并创建一个实现Stringer接口的函数类型,Go格式库在需要打印时会调用它。

我找不到一种我真正喜欢的创建函数类型的方法,也许其他人知道一些更好的技巧。

package main

import (
	"fmt"
	"os"
	"time"
)

type thing func() string

func (t thing) String() string {
	return t()
}

func toThing(f func() string) thing {
	return f
}

func maybePrint(p bool, args ...interface{}) {
	if p {
		fmt.Println(args...)
	}
}

func main() {
	maybePrint(len(os.Args) > 2, "testing", toThing(func() string {
		fmt.Println("Calculating big thing")
		time.Sleep(time.Second)
		return "test"
	}))
}
英文:

I was curious and playing around with this. I don't know if this would work for you but it's interesting.

By using a lambda function, and making a function type that implements the Stringer interface, the Go format library will call it when it needs to print it.

I could not find a way I really liked to create the function type, maybe someone else knows some better trick.

package main

import (
	"fmt"
	"os"
	"time"
)

type thing func() string

func (t thing) String() string {
	return t()
}

func toThing(f func() string) thing {
	return f
}

func maybePrint(p bool, args ...interface{}) {
	if p {
		fmt.Println(args...)
	}
}

func main() {
	maybePrint(len(os.Args) > 2, "testing", toThing(func() string {
		fmt.Println("Calculating big thing")
		time.Sleep(time.Second)
		return "test"
	}))
}

huangapple
  • 本文由 发表于 2017年3月17日 12:52:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/42849456.html
匿名

发表评论

匿名网友

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

确定