Skip to content

Commit

Permalink
refactor(writers): 采用 io.MultiWriter 代替 New 自有的实现
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Nov 1, 2023
1 parent d4cadc9 commit b8e2d80
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 66 deletions.
14 changes: 10 additions & 4 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import (
"sync"

"github.com/issue9/term/v3/colors"

"github.com/issue9/logs/v6/writers"
)

var nop = &nopHandler{}
Expand Down Expand Up @@ -48,7 +46,11 @@ func (w HandlerFunc) Handle(e *Record) { w(e) }
//
// NOTE: 如果向 w 输出内容时出错,会将错误信息输出到终端作为最后的处理方式。
func NewTextHandler(w ...io.Writer) Handler {
ww := writers.New(w...)
if len(w) == 0 {
return nop
}

ww := io.MultiWriter(w...)
mux := &sync.Mutex{} // 防止多个函数同时调用 HandlerFunc 方法。

return HandlerFunc(func(e *Record) {
Expand Down Expand Up @@ -124,7 +126,11 @@ func NewTextHandler(w ...io.Writer) Handler {
//
// NOTE: 如果向 w 输出内容时出错,会将错误信息输出到终端作为最后的处理方式。
func NewJSONHandler(w ...io.Writer) Handler {
ww := writers.New(w...)
if len(w) == 0 {
return nop
}

ww := io.MultiWriter(w...)
mux := &sync.Mutex{}

return HandlerFunc(func(e *Record) {
Expand Down
8 changes: 2 additions & 6 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@ func TestTextHandler(t *testing.T) {
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))

a.PanicString(func() {
NewTextHandler()
}, "参数 w 不能为空")
a.Equal(NewTextHandler(), nop)

buf := new(bytes.Buffer)
l.SetHandler(NewTextHandler(buf))
Expand Down Expand Up @@ -96,9 +94,7 @@ func TestJSONFormat(t *testing.T) {
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))

a.PanicString(func() {
NewJSONHandler()
}, "参数 w 不能为空")
a.Equal(NewJSONHandler(), nop)

buf := new(bytes.Buffer)
l.SetHandler(NewJSONHandler(buf))
Expand Down
28 changes: 4 additions & 24 deletions writers/writers.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,11 @@ package writers

import "io"

type (
ws []io.Writer

WriteFunc func([]byte) (int, error)
)
type WriteFunc func([]byte) (int, error)

func (f WriteFunc) Write(data []byte) (int, error) { return f(data) }

func (w ws) Write(data []byte) (n int, err error) {
for _, writer := range w {
if n, err = writer.Write(data); err != nil {
return n, err
}
}
return n, err
}

// New 将 [1,n] 个 [io.Writer] 合并成一个
func New(w ...io.Writer) io.Writer {
switch len(w) {
case 0:
panic("参数 w 不能为空")
case 1:
return w[0]
default:
return ws(w)
}
}
//
// Deprecated: 请使用 [io.MultiWriter] 代替
func New(w ...io.Writer) io.Writer { return io.MultiWriter(w...) }
32 changes: 0 additions & 32 deletions writers/writers_test.go

This file was deleted.

0 comments on commit b8e2d80

Please sign in to comment.