15

It is useful to leave low-level debug/trace logging statements in critical paths so that they can be enabled by runtime configuration. The idea is you never turn such logging on in production (it would cripple performance) but you can turn it on in a production environment (e.g. production system taken offline for debugging or a test system that is set up exactly like the production system.)

This type of logging has a special requirement: the cost of hitting a disabled log statement on a critical path must be very low: ideally a single boolean test.

In C/C++ I would do this with a LOG macro that does not evaluate any of its arguments until it has checked a flag. Only if enabled do we call some helper function to format & deliver the log message.

So how to do this in Go?

Using io.Discard with log.Logger is a non starter: it completely formats the log message every time before throwing it away if disabled.

My first thought is

type EnabledLogger struct { Enabled bool; delegate *log.Logger;... }
// Implement the log.Logger interface methods as:
func (e EnabledLogger) Print(...) { if e.Enabled { e.delegate.Output(...) } }

This is close. If I say:

myEnabledLogger.Printf("foo %v: %v", x, y)

It won't format or log anything if disabled but it will evaluate the arguments x and y. That's OK for basic types or pointers, not OK for arbitrary function calls - e.g. to stringify values that don't have a String() method.

I see two ways around that:

Wrapper types to defer the call:

type Stringify { x *Thing }
func (s Stringify) String() { return someStringFn(s.x) }
enabledLogger.Printf("foo %v", Stringify{&aThing})

Wrap the whole thing in a manual enabled check:

if enabledLog.Enabled {
     enabledLog.Printf("foo %v", someStringFn(x))
}

Both are verbose and error prone, it is too easy for someone to forget a step and quietly introduce a nasty performance regression.

I'm starting to like Go. Please tell me it can solve this problem :)

3
  • Without resorting to macros a solution could be to change the log variable in one point : it could be either a real log function or a noop. Note also that the go compiler would remove the whole if (someconstantwhichisfalse) { log(...) } block. Apr 29, 2015 at 14:31
  • Small functions will usually be inlined by gc (the Go compiler), so calling a function which checks a bool and forwards will usually be equaly fast as checking a bool around a the log-call.
    – thwd
    Apr 29, 2015 at 14:49
  • If you have a someStringFn to format a value of type Thing, why don't you just define a String method on it? That would be more idiomatic and would also solve your problem.
    – Ainar-G
    Apr 29, 2015 at 15:22

2 Answers 2

2

All arguments in Go are guaranteed to be evaluated, and there's no defined preprocessor macros in the language, so there's only a couple things you can do.

To avoid expensive function calls in the logging arguments, make use of the fmt.Stringer and fmt.GoStringer interfaces to delay formatting until the function is executed. That way you can still pass the plain types to Printf functions. You can extend this pattern yourself with a custom logger that checks for various interfaces as well. This is what you're using in your Stringify example, and you can only really enforce it with code review and unit tests.

type LogFormatter interface {
    LogFormat() string
}

// inside the logger
if i, ok := i.(LogFormatter); ok {
    fmt.Println(i.LogFormat())
}

You can also swap out the entire logger out at runtime via a logger interface, or replace it entirely at build time using build constraints, but still requires ensuring no expensive calls are inserted into the logging arguments.

Another pattern used by some packages like glog is to make the Logger itself a bool. This doesn't eliminate the verbosity completely, but it makes it a little more terse.

type Log bool
func (l Log) Println(args ...interface{}) {
    fmt.Println(args...)
}

var debug Log = false

if debug {
    debug.Println("DEBUGGING")
}

The closest you can get to a macro pre-processing in go is to use code generation. This isn't going to work for runtime configurable tracing, but could at least provide a separate debug build that can be dropped into place when needed. It can be as simple as gofmt -r, building a file using text/template, or full generation by parsing the code and building an AST.

4
  • I think in your type Log bool example you might be missing an if l {…}?
    – Dave C
    Apr 29, 2015 at 16:33
  • @DaveC, Since you need to wrap the call in an if anyway to prevent the args from being evaluated, you technically don't need to check it again in the method call. I think having it still print if you forget the check is more helpful since it enforces the if check idiom, but neither way would be wrong.
    – JimB
    Apr 29, 2015 at 16:39
  • Oh, sorry, I thought you were trying to make it like glog supporting one line use (and rely on the compiler to inline the boolean comparison and forwarding function call). Although, glog provides both ways since the inlining would still evaluate arguments.
    – Dave C
    Apr 29, 2015 at 17:08
  • I would like to allow the one liner since most of the time log messages do have simple args. It relies on people not to forget the if when they do something more complex. I've done things like that before even in C++, if you need to do something more than just a function call you put an explicit if around the lot. I think that's what I'll go for. Thanks all! Apr 30, 2015 at 15:36
1

First of all, I should say that I personally would go with the simplest solution and just use an if. But if you really want to do it reliably, you can use anonymous functions:

type verbose bool

func (v verbose) Run(f func()) {
    if v {
        f()
    }
}

Use it like this:

v := verbose(false)
v.Run(func() {
    log.Println("No Print")
})

Playground example with expensive calls: http://play.golang.org/p/9pm2HoQQ8A.

1
  • 1
    Clever! But more verbose than the if. I guess a simple boolean flag and explicit if is the way to go. Apr 29, 2015 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.