dts777777 2016-02-07 21:48
浏览 56
已采纳

转到:使用multiWriter将作家添加到io.writer

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.

  • 写回答

2条回答 默认 最新

  • drt96856 2016-02-07 22:28
    关注

    You don't seem to have a map of writers, you have a map of ints to bools. Presumably, the ints represent the file descriptor.

    The easiest way to do it would probably to change it from map[int]bool to map[io.Writer]bool, then you can iterate through them and add them to a slice with append.

    ws := make([]io.Writer, 0)
    for k, v : = range(writers) {
        if v != true {
            continue
        }
        ws = append(ws, k)
    }
    

    After that, you can just create a multiwriter directly by giving the slice to your MultiWriter call.

    w := io.MultiWriter(ws...)
    log.SetOutput(w)
    

    (The ... in a function parameter after a slice means to expand the slice into arguments to the function call)

    You can do the same thing while keeping it map[int]bool, but you'll need a switch similar to what you already have to convert your int into an io.Writer

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击