How can i be able to enable and disable loggin in my package

Hello everyone
i new to golang and i want to achieve this.
modify the package such that a user can be able to enable and disable loggin in the package, such that when loggin is enable, the package should log the answer in a file after processing before returning the result.

type Divider struct{
log bool
}
func NewDivider(islog bool) *Divider{
return &Divider{log: islog}
}
func (d *Divider) Divide(firstValue, secondValue float64) (float64) {
result = firstValue+secondValue
if d.log} {
log.Println(result)}
{
return result
}

You can take an input from a user on whether to write any application logs to a file(in the form of a boolean) and then store that in a global variable and check every time whether you should write the log to a file or not. You can also write a custom log function to avoid writing that code every time.

You can also use a config file to let the user define such a condition.

1 Like

thanks, but can you show me an example?

package whatever

var loggingEnabled bool=true

func EnableLogging() {
  loggingEnabled=true
}
func DisableLogging() {
  loggingEnabled=false
}
func AnyWhateverAPIFunction() {
  if loggingEnabled {
    writeLog()
  }
}
1 Like

thank you

The log package allows to define a NOOP logger

logger = log.New(io.Discard, "", log. LstdFlags)

then you can pass this logger to your API

In this way you’ll not need to check every time if the logging is enabled or not

func MakeLogger(enabled bool) *log.Logger {
    writer := io.Discard
    if enabled {
         writer := io.StdErr
    }
    return log.New(writer, "", log.LstdFlags)
}

func main() {
    var logEnabled bool
    // read enabled from Flags or Environment Variable
    logger := MakeLogger(logEnabled)

    yourApi(logger)
}

func yourApi(logger log.logger) {
     logger.Print("Hello")
}

Thank you so much.

Nice