如何向io.MultiWriter添加/删除按需编写器?

时间:2016-07-17 11:16:03

标签: logging go

我正在使用以下内容将日志写入文件和程序的标准输入:

type myLogger {
    log  *log.Logger
}

cmd := exec.Command("logger", "-t", "test")
w, _ = cmd.StdinPipe()

multi := io.MultiWriter(file, w)

myLog := myLogger{log.New(multi, "", log.Ldate|log.Ltime)}

但是如果命令退出,被杀或者我只是想添加另一个this package,我怎么能将它附加到现有的Writer

目前,对于每次更改,我都会创建一个新的multi并覆盖现有的记录器:

multi := io.MultiWriter(file, w)
myLog.log = log.New(multi, "", log.Ldate|log.Ltime)

但是想知道是否有更好的方法可以做到这一点,如果通过创建新的log.New,我应该关闭之前的那些,还是只是分享我传递给Writers的引用multi var?

1 个答案:

答案 0 :(得分:0)

您可以编写自己的包并添加这两个RemoveAppend方法,例如此工作测试示例代码(非并发):

package main

import (
    "io"
    "os"
)

func main() {
    w1, e := os.Create("file1.txt")
    if e != nil {
        panic(e)
    }
    w2, e := os.Create("file2.txt")
    if e != nil {
        panic(e)
    }
    mw := MultiWriter(w1, w2)
    data := []byte("Hello ")
    _, e = mw.Write(data)
    if e != nil {
        panic(e)
    }

    var m *multiWriter = mw.(*multiWriter)
    m.Remove(w2)
    w2.Close()
    w3, e := os.Create("file3.txt")
    if e != nil {
        panic(e)
    }
    m.Append(w3)
    data = []byte("World ")
    _, e = mw.Write(data)
    if e != nil {
        panic(e)
    }
    w3.Close()
    w1.Close()
}
func (t *multiWriter) Remove(writers ...io.Writer) {
    for i := len(t.writers) - 1; i > 0; i-- {
        for _, v := range writers {
            if t.writers[i] == v {
                t.writers = append(t.writers[:i], t.writers[i+1:]...)
                break
            }
        }
    }
}
func (t *multiWriter) Append(writers ...io.Writer) {
    t.writers = append(t.writers, writers...)
}

type multiWriter struct {
    writers []io.Writer
}

func (t *multiWriter) Write(p []byte) (n int, err error) {
    for _, w := range t.writers {
        n, err = w.Write(p)
        if err != nil {
            return
        }
        if n != len(p) {
            err = io.ErrShortWrite
            return
        }
    }
    return len(p), nil
}

var _ stringWriter = (*multiWriter)(nil)

func (t *multiWriter) WriteString(s string) (n int, err error) {
    var p []byte // lazily initialized if/when needed
    for _, w := range t.writers {
        if sw, ok := w.(stringWriter); ok {
            n, err = sw.WriteString(s)
        } else {
            if p == nil {
                p = []byte(s)
            }
            n, err = w.Write(p)
        }
        if err != nil {
            return
        }
        if n != len(s) {
            err = io.ErrShortWrite
            return
        }
    }
    return len(s), nil
}

// MultiWriter creates a writer that duplicates its writes to all the
// provided writers, similar to the Unix tee(1) command.
func MultiWriter(writers ...io.Writer) io.Writer {
    w := make([]io.Writer, len(writers))
    copy(w, writers)
    return &multiWriter{w}
}

// stringWriter is the interface that wraps the WriteString method.
type stringWriter interface {
    WriteString(s string) (n int, err error)
}

并发安全:

package main

import (
    "io"
    "os"
    "sync"
)

func main() {
    w1, e := os.Create("file1.txt")
    if e != nil {
        panic(e)
    }
    w2, e := os.Create("file2.txt")
    if e != nil {
        panic(e)
    }
    mw := MultiWriter(w1, w2)
    data := []byte("Hello ")
    _, e = mw.Write(data)
    if e != nil {
        panic(e)
    }

    var m *multiWriter = mw.(*multiWriter)
    m.Remove(w2)
    w2.Close()
    w3, e := os.Create("file3.txt")
    if e != nil {
        panic(e)
    }
    m.Append(w3)
    data = []byte("World ")
    _, e = mw.Write(data)
    if e != nil {
        panic(e)
    }
    w3.Close()
    w1.Close()
}
func (t *multiWriter) Remove(writers ...io.Writer) {
    t.mu.Lock()
    defer t.mu.Unlock()
    for i := len(t.writers) - 1; i > 0; i-- {
        for _, v := range writers {
            if t.writers[i] == v {
                t.writers = append(t.writers[:i], t.writers[i+1:]...)
                break
            }
        }
    }
}
func (t *multiWriter) Append(writers ...io.Writer) {
    t.mu.Lock()
    defer t.mu.Unlock()
    t.writers = append(t.writers, writers...)
}

type multiWriter struct {
    writers []io.Writer
    mu      sync.Mutex
}

func (t *multiWriter) Write(p []byte) (n int, err error) {
    t.mu.Lock()
    defer t.mu.Unlock()
    for _, w := range t.writers {
        n, err = w.Write(p)
        if err != nil {
            return
        }
        if n != len(p) {
            err = io.ErrShortWrite
            return
        }
    }
    return len(p), nil
}

var _ stringWriter = (*multiWriter)(nil)

func (t *multiWriter) WriteString(s string) (n int, err error) {
    t.mu.Lock()
    defer t.mu.Unlock()
    var p []byte // lazily initialized if/when needed
    for _, w := range t.writers {
        if sw, ok := w.(stringWriter); ok {
            n, err = sw.WriteString(s)
        } else {
            if p == nil {
                p = []byte(s)
            }
            n, err = w.Write(p)
        }
        if err != nil {
            return
        }
        if n != len(s) {
            err = io.ErrShortWrite
            return
        }
    }
    return len(s), nil
}

// MultiWriter creates a writer that duplicates its writes to all the
// provided writers, similar to the Unix tee(1) command.
func MultiWriter(writers ...io.Writer) io.Writer {
    w := make([]io.Writer, len(writers))
    copy(w, writers)
    return &multiWriter{writers: w}
}

// stringWriter is the interface that wraps the WriteString method.
type stringWriter interface {
    WriteString(s string) (n int, err error)
}