writer.go 667 B

123456789101112131415161718192021222324252627282930313233343536
  1. package log
  2. import (
  3. "io"
  4. "os"
  5. "sync"
  6. )
  7. type MultipleWriter struct {
  8. io.Writer // 默认输出到标准输出
  9. sync.Map // 用于存储多个输出
  10. }
  11. func (m *MultipleWriter) Write(p []byte) (n int, err error) {
  12. n, err = m.Writer.Write(p)
  13. m.Range(func(key, value any) bool {
  14. if _, err := key.(io.Writer).Write(p); err != nil {
  15. m.Delete(key)
  16. }
  17. return true
  18. })
  19. return
  20. }
  21. func (m *MultipleWriter) Add(writer io.Writer) {
  22. m.Map.Store(writer, struct{}{})
  23. }
  24. var multipleWriter = &MultipleWriter{Writer: os.Stdout}
  25. func AddWriter(writer io.Writer) {
  26. multipleWriter.Add(writer)
  27. }
  28. func DeleteWriter(writer io.Writer) {
  29. multipleWriter.Delete(writer)
  30. }