I have some heavily instrumented code that makes use of the log
package. Now it's come time to turn off the logging, and I can't determine how to turn off the standard logger.
Have I missed something? Should I be checking a flag before making log calls, or commenting them out in production?
This approach allows you to turn logging on and off at runtime:
And this approach enables or disables logging for the entire runtime:
Where
some.Constant
would be either a constant that you set before compiling (producing a "production" binary) or a variable that is set only once when running the program via command-line flags (something likemyprogram --enable-logging=true
)With both approaches you can leave your current code almost entirely untouched.
No reason to create your own type for a common io.Writer when one exists in the io/ioutil package.
A note for others coming here looking for this and other logging facilities: have a look at the log4go package as that covers turning off logging, setting log levels, log rotation, redirection to a file etc which might be useful.
See the doc at http://godoc.org/code.google.com/p/log4go
Since
SetOutput()
is only defined for the global logger, a custom writer is still handy for other loggers. A short way of writing one is like this:For completely disabling logs, it's actually better to call
log.SetFlags(0)
Joril and set the output to a no-opio.Writer
(i.e.,log.SetOutput(ioutil.Discard)
)But even after this, the operations will idle around 500-600 ns/op1
This can still be cut short (to around 100 ns/op) by using a custom
Logger
implementation, and implementing all the functions to be no-op -- as demonstrated here (only overridingPrintln
for bervity).The alternative to all these is to use a custom logging framework with levels and set it to complete OFF.
Note though, one of the commonly used library for logging (logrus) has performance implications -- the same can be found in the benchmarks where it perform with 3K+ ns/op, regardless.
Biased opinion: from the benchmarks, the library go-logging performs in par with the custom
Logger
implementation when setting theLevel
to-1
, regardless of the backend and formatting(the benchmark source can be found here)
the output of the benchmark is as follows:
#1: YMMV, tested on i7-4500U CPU @ 1.80GHz