I'm new to Go. I have a map which indicates which writers are active:
var writers map[int]bool
I want to iterate over the map, and create a writer which represents all active writers using multiWriter()
I am using the following code snippet:
func setupMultiLoggers() {
var mw io.Writer
for k, v := range writers {
if v != true {
continue
}
switch k {
case 0:
if mw == nil {
mw = writer0
} else {
mw = io.MultiWriter(mw, writer0)
}
case 1:
if mw == nil {
mw = os.Stdout
} else {
mw = io.MultiWriter(mw, os.Stdout)
}
case 2:
if mw == nil {
mw = writer2
} else {
io.MultiWriter(mw, writer2)
}
default:
}
}
log.SetOutput(mw)
}
When initializing the all 3 values of the map to true and then testing writer2, it sometimes works and sometimes doesn't (code in case 2 always executes)
If I just use
log.SetOutput(io.MultiWriter(writer0, os.Stdout, writer2))
It always works as expected.
I cannot seem to understand why my original code doesn't reliably work. I have a feeling there is a more clean way to "concatenate" writers
EDIT: I've found my (stupid) bug. assignment to mw was missing in the third case. Still looking for a more clean way to "concatenate" writers.