How to turn on conditional logging?

338 views
Skip to first unread message

Chun Zhang

unread,
Jun 7, 2017, 5:07:43 PM6/7/17
to golang-nuts
Hi, All, 

I have some piece of code with very high cpu usage, logging is actually pretty cpu intensive, so I tried to turn it off as follows, 

type myLog struct {
*log.Logger
enable bool
}

func (l *myLog) Println(v ...interface{}) {
if l.enable == true {
l.Output(2, fmt.Sprintln(v...))
}
}

Debug = myLog{log.New(debugHandle,
"DEBUG: ",
log.Ldate|log.Ltime|log.Lshortfile), false}
if debugOn == true {
Debug.enable = true
Debug.SetOutput(&lumberjack.Logger{
Filename: "/var/log/sflow/sFlowDecoder.debug",
MaxSize: MAX_LOG_SIZE, // megabytes after which new file is created
MaxBackups: MAX_LOG_BACKUP, // number of backups
MaxAge: MAX_LOG_KEEP_TIME, //days
})
} else {
Debug.enable = false
}


I was expecting Debug.Println will be compiled with zero footprint in the code, or at least a NOP. As far as I can see, the debugs are not logged into the file. However, when I did profiling, it still takes significant cpu resource. 
by doing 
(pprof) list main.pktDistribute
<snip> 

     10ms      1.59s    547: Debug.Println("put packet on the queue", tmpData)

<snip>

I am wondering what I did wrong? What would be a proper solution to completely turn this off?

Thanks,
Chun

Val

unread,
Jun 7, 2017, 6:36:32 PM6/7/17
to golang-nuts
Hello Chun
In your code, myLog.enable is not a constant (I mean, not a go constant) so I can understand that the compiler doesn't "optimize away" all the calls to (*myLog).Println.

However, I recently tried to achieve the same with a constant (toggled only by the developer before compilation) inside the custom Println, expecting the disabled logging to be optimized away as suggested by the "Dead code elimination" part of Five things that make Go fast. Unfortunately I could not achieve the desired result and haven't yet looked closely at the results of "go build -gcflags -m" to figure out why the custom Println was not inlined and eliminated as dead code.

FWIW, I sometimes use the following ugly pattern for assertions  (it might be adapted for conditional logging) :
  _ = value==expected || fail("with", "some", "variadic", "info")

Val
Reply all
Reply to author
Forward
0 new messages