Skip to content

Commit

Permalink
Feat: 支持链式调用
Browse files Browse the repository at this point in the history
  • Loading branch information
Boii committed Feb 8, 2022
1 parent 2e63a8d commit f82a821
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
24 changes: 16 additions & 8 deletions elog.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,48 +265,56 @@ func (l *Log) Flag() int {
defer l.mu.Unlock()
return l.flag
}
func (l *Log) SetOutput(w io.Writer) {
func (l *Log) SetOutput(w io.Writer) *Log {
l.mu.Lock()
defer l.mu.Unlock()
l.output = w
return l
}
func (l *Log) SetLevel(level logLevel) {
func (l *Log) SetLevel(level logLevel) *Log {
l.mu.Lock()
defer l.mu.Unlock()
l.level = level
return l
}
func (l *Log) SetName(name string) {
func (l *Log) SetName(name string) *Log {
l.mu.Lock()
defer l.mu.Unlock()
l.name = name
return l
}
func (l *Log) SetPrefix(prefix string) {
func (l *Log) SetPrefix(prefix string) *Log {
l.mu.Lock()
defer l.mu.Unlock()
l.prefix = prefix
return l
}
func (l *Log) SetFlag(flag int) {
func (l *Log) SetFlag(flag int) *Log {
l.mu.Lock()
defer l.mu.Unlock()
l.flag = flag
return l
}
func (l *Log) SetOrder(orders ...logOrder) {
func (l *Log) SetOrder(orders ...logOrder) *Log {
l.mu.Lock()
defer l.mu.Unlock()
l.order = l.order[:0]
l.order = append(l.order, orders...)
return l
}

// Manipulate Flag
func (l *Log) AddFlag(flag int) {
func (l *Log) AddFlag(flag int) *Log {
l.mu.Lock()
defer l.mu.Unlock()
l.flag = l.flag | flag
return l
}
func (l *Log) SubFlag(flag int) {
func (l *Log) SubFlag(flag int) *Log {
l.mu.Lock()
defer l.mu.Unlock()
l.flag = l.flag &^ flag
return l
}

// 这个方法仅限于 Out() 方法用,因为在 Out 方法中已经上锁了,所以这里不能再上锁
Expand Down
12 changes: 12 additions & 0 deletions elog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,18 @@ func TestExtend(t *testing.T) {
}
}

func TestMethodChaining(t *testing.T) {
var b bytes.Buffer
parent := New(&b, InfoLevel).SetFlag(Llevel).SetName("chaining")
if parent.Flag() != Llevel || parent.Name() != "chaining" {
t.Errorf("the method chaining may have some problem when logger parent creating. parent: %q", parent)
}
child := parent.Extend().AddFlag(Ldate)
if child.Flag() != Llevel|Ldate {
t.Errorf("the method chaining may have some problem when logger child extending. child: %q", child)
}
}

func TestOut(t *testing.T) {
const testString = "test"
var b bytes.Buffer
Expand Down

0 comments on commit f82a821

Please sign in to comment.