2

I'm using go-logging and I'm trying to build a logger with a variable number of Backends (i.e. stderr + file + syslog + ...). So my program reads a configuration file, and create the logger according to what's defined.

As SetBackend is a variadic function, I thought I could use a slice as argument, but I was wrong.

Here is an example of my code:

func configureLogger(debug, file bool) {
    var backendList = []logging.Backend{}
    var format = logging.MustStringFormatter(
        `%{color}%{time:15:04:05.000} [%{level:.4s}] %{shortfunc}%{color:reset}: %{message}`,
    )

    if debug {
        consoleBackend := logging.NewLogBackend(os.Stderr, "", 0)
        consoleBackendFormatter := logging.NewBackendFormatter(consoleBackend, format)
        consoleBackendLeveled := logging.AddModuleLevel(consoleBackendFormatter)
        consoleBackendLeveled.SetLevel(logging.DEBUG, "")
        backendList = append(backendList, consoleBackendLeveled)
    }

    if file {
        f, err := os.OpenFile("file.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
        filebackend := logging.NewLogBackend(f, "", 0)
        filebackendFormatter := logging.NewBackendFormatter(filebackend, format)
        filebackendLeveled := logging.AddModuleLevel(filebackendFormatter)
        filebackendLeveled.SetLevel(logging.DEBUG, "")
        backendList = append(backendList, filebackendLeveled)
    }

    logging.SetBackend(backendList)
}

This end up with the following error:

cannot use backendList (type []logging.Backend) as type logging.Backend in argument to logging.SetBackend:
    []logging.Backend does not implement logging.Backend (missing Log method)

What am I missing?

1 Answer 1

2

I was missing the good syntax. When passing a slice to a variadic function, you need to add ... after your slice name, as shown in the specs: https://golang.org/ref/spec#Passing_arguments_to_..._parameters

The right syntax is:

logging.SetBackend(backendList...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.