Tag Archives: Logger

A barebone logger for Go

While working on a Go library, I was looking for an elegant solution for logging. After following many discussions on the forum, I came up with the following barebone which I think is decent performant and clean. Check it out!

package main

import (
        "flag"
        "log"
)

type Logger struct {
        log_func func(string, ...interface{})
}

func do_log(fmt string, args ...interface{}) {
        log.Printf(fmt, args...)
}

func do_not_log(fmt string, args ...interface{}) {
        // Do nothing..
}

func (logger *Logger) init_logger(enable_log bool) {
        if enable_log == true {
                logger.log_func = do_log
        } else {
                logger.log_func = do_not_log
        }
}

func main() {
        logger := new(Logger)

        // command line option
        enable_log := flag.Bool("enable_log", false, "Enable logging")
        flag.Parse()

        logger.init_logger(*enable_log)

        logger.log_func("%s", "log me!")
        logger.log_func("%s", "log me again..!")
}

Output:

$ ./logger
$ ./logger –enable_log
2013/01/28 11:41:19 log me!
2013/01/28 11:41:19 log me again..!
$