How to disable a log.Logger

后端 未结 6 1606
长情又很酷
长情又很酷 2020-12-23 16:35

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

6条回答
  •  醉梦人生
    2020-12-23 17:07

    This approach allows you to turn logging on and off at runtime:

    type LogWriter struct{
        enabled bool
    }
    
    func (l *LogWriter) Enable() {
        l.enabled = true
    }
    
    func (l *LogWriter) Disable() {
        l.enabled = false
    }
    
    func (l *LogWriter) Write([]byte) (int, error) {
        if l.enabled {
            //...
        }
        return 0, nil
    }
    

    And this approach enables or disables logging for the entire runtime:

    type LogWriter struct{}
    
    func (l *LogWriter) Write([]byte) (int, error) {
        if some.Constant {
            //...
        }
        return 0, nil
    }
    

    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 like myprogram --enable-logging=true)

    With both approaches you can leave your current code almost entirely untouched.

提交回复
热议问题