Skip to content

Commit

Permalink
refactor: Record 不再实现 Recorder
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Nov 7, 2023
1 parent b5439e1 commit 85a17f8
Show file tree
Hide file tree
Showing 7 changed files with 213 additions and 201 deletions.
31 changes: 16 additions & 15 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ type (
Handler interface {
// Handle 将 [Record] 写入日志
//
// [Record] 中各个字段的名称由处理器自行决定。
// [Record] 中各个字段的名称由处理器自行决定;
// detail 表示是否显示错误的堆栈信息;
//
// NOTE: 此方法应该保证输出内容是以换行符作为结尾。
Handle(*Record)
Handle(detail bool, r *Record)

// WithAttrs 根据参数生成新的 [Handler] 对象
//
Expand Down Expand Up @@ -81,8 +82,8 @@ func NewTextHandler(w ...io.Writer) Handler {
return &textHandler{w: writers.New(w...)}
}

func (h *textHandler) Handle(e *Record) {
b := NewBuffer(e.Logs().Detail())
func (h *textHandler) Handle(detail bool, e *Record) {
b := NewBuffer(detail)
defer b.Free()

b.AppendBytes('[').AppendString(e.Level.String()).AppendBytes(']')
Expand Down Expand Up @@ -177,8 +178,8 @@ func NewJSONHandler(w ...io.Writer) Handler {
return &jsonHandler{w: writers.New(w...)}
}

func (h *jsonHandler) Handle(e *Record) {
b := NewBuffer(e.Logs().Detail())
func (h *jsonHandler) Handle(detail bool, e *Record) {
b := NewBuffer(detail)
defer b.Free()

b.AppendBytes('{')
Expand Down Expand Up @@ -295,8 +296,8 @@ func NewTermHandler(w io.Writer, foreColors map[Level]colors.Color) Handler {
return &termHandler{w: w, foreColors: cs}
}

func (h *termHandler) Handle(e *Record) {
b := NewBuffer(e.Logs().Detail())
func (h *termHandler) Handle(detail bool, e *Record) {
b := NewBuffer(detail)
defer b.Free()

ww := colors.New(b)
Expand All @@ -305,22 +306,22 @@ func (h *termHandler) Handle(e *Record) {

var indent byte = ' '
if e.AppendCreated != nil {
b := NewBuffer(e.Logs().Detail())
b := NewBuffer(detail)
defer b.Free()
e.AppendCreated(b)
ww.WByte(' ').WBytes(b.data)
indent = '\t'
}

if e.AppendLocation != nil {
b := NewBuffer(e.Logs().Detail())
b := NewBuffer(detail)
defer b.Free()
e.AppendLocation(b)
ww.WByte(' ').WBytes(b.data)
indent = '\t'
}

bb := NewBuffer(e.Logs().Detail())
bb := NewBuffer(detail)
defer bb.Free()
e.AppendMessage(bb)
ww.WByte(indent).WBytes(bb.data)
Expand Down Expand Up @@ -354,7 +355,7 @@ func NewDispatchHandler(d map[Level]Handler) Handler {
return &dispatchHandler{handlers: d}
}

func (h *dispatchHandler) Handle(e *Record) { h.handlers[e.Level].Handle(e) }
func (h *dispatchHandler) Handle(detail bool, e *Record) { h.handlers[e.Level].Handle(detail, e) }

func (h *dispatchHandler) WithAttrs(attrs []Attr) Handler {
m := make(map[Level]Handler, len(h.handlers))
Expand All @@ -367,9 +368,9 @@ func (h *dispatchHandler) WithAttrs(attrs []Attr) Handler {
// MergeHandler 将多个 Handler 合并成一个 Handler 接口对象
func MergeHandler(w ...Handler) Handler { return &mergeHandler{handlers: w} }

func (h *mergeHandler) Handle(e *Record) {
func (h *mergeHandler) Handle(detail bool, e *Record) {
for _, hh := range h.handlers {
hh.Handle(e)
hh.Handle(detail, e)
}
}

Expand All @@ -384,6 +385,6 @@ func (h *mergeHandler) WithAttrs(attrs []Attr) Handler {
// NewNopHandler 空的 Handler 接口实现
func NewNopHandler() Handler { return nop }

func (h *nopHandler) Handle(_ *Record) {}
func (h *nopHandler) Handle(bool, *Record) {}

func (h *nopHandler) WithAttrs([]Attr) Handler { return h }
62 changes: 31 additions & 31 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ func (o marshalErrObject) MarshalJSON() ([]byte, error) {
return nil, errors.New("marshal json error")
}

func newRecord(a *assert.Assertion, logs *Logs, lv Level) *Record {
e := logs.NewRecord(lv, logs.handler)
func newRecord(a *assert.Assertion, lv Level) *Record {
e := NewRecord(lv)
a.NotNil(e)

e.AppendMessage = func(b *Buffer) { b.AppendString("msg") }
Expand All @@ -58,26 +58,26 @@ func TestTextHandler(t *testing.T) {
now := time.Now()

l := New(nil, WithCreated(layout), WithLocation(true))
e := newRecord(a, l, LevelWarn)
e := newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))
e.with(l, "m1", marshalObject("m1"))

buf := new(bytes.Buffer)
l = New(NewTextHandler(buf), WithCreated(layout), WithLocation(true))
e = newRecord(a, l, LevelWarn)
e = newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))
e.output()
e.with(l, "m1", marshalObject("m1"))
e.output(l.detail, l.handler)
a.Equal(buf.String(), "[WARN] "+now.Format(layout)+" path.go:20\tmsg k1=v1 k2=v2 m1=m1\n")

b1 := new(bytes.Buffer)
b2 := new(bytes.Buffer)
b3 := new(bytes.Buffer)
l = New(NewTextHandler(b1, b2, b3), WithCreated(layout), WithLocation(true))
e = newRecord(a, l, LevelWarn)
e = newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))
e.output()
e.with(l, "m1", marshalObject("m1"))
e.output(l.detail, l.handler)
a.Equal(b1.String(), "[WARN] "+now.Format(layout)+" path.go:20\tmsg k1=v1 k2=v2 m1=m1\n")
a.Equal(b2.String(), "[WARN] "+now.Format(layout)+" path.go:20\tmsg k1=v1 k2=v2 m1=m1\n")
a.Equal(b3.String(), "[WARN] "+now.Format(layout)+" path.go:20\tmsg k1=v1 k2=v2 m1=m1\n")
Expand All @@ -86,11 +86,11 @@ func TestTextHandler(t *testing.T) {

buf.Reset()
l = New(NewTextHandler(buf), WithCreated(layout), WithLocation(true))
e = newRecord(a, l, LevelWarn)
e = newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))
e.With("m2", marshalErrObject("m2"))
e.output()
e.with(l, "m1", marshalObject("m1"))
e.with(l, "m2", marshalErrObject("m2"))
e.output(l.detail, l.handler)
a.Equal(buf.String(), "[WARN] "+now.Format(layout)+" path.go:20\tmsg k1=v1 k2=v2 m1=m1 m2=Err(marshal text error)\n")
}

Expand All @@ -100,39 +100,39 @@ func TestJSONFormat(t *testing.T) {
now := time.Now()

l := New(nil, WithCreated(layout), WithLocation(true))
e := newRecord(a, l, LevelWarn)
e := newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))
e.with(l, "m1", marshalObject("m1"))

a.Panic(func() { NewJSONHandler() })

buf := new(bytes.Buffer)
l = New(NewJSONHandler(buf), WithCreated(layout), WithLocation(true))
e = newRecord(a, l, LevelWarn)
e = newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))
e.output()
e.with(l, "m1", marshalObject("m1"))
e.output(l.detail, l.handler)
a.Equal(buf.String(), `{"level":"WARN","message":"msg","created":"`+now.Format(layout)+`","path":"path.go:20","attrs":[{"k1":"v1"},{"k2":"v2"},{"m1":"m1"}]}`)

b1 := new(bytes.Buffer)
b2 := new(bytes.Buffer)
l = New(NewJSONHandler(b1, b2), WithCreated(layout), WithLocation(true))
e = newRecord(a, l, LevelWarn)
e = newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))
e.output()
e.with(l, "m1", marshalObject("m1"))
e.output(l.detail, l.handler)
a.Equal(b1.String(), `{"level":"WARN","message":"msg","created":"`+now.Format(layout)+`","path":"path.go:20","attrs":[{"k1":"v1"},{"k2":"v2"},{"m1":"m1"}]}`).
Equal(b1.String(), b2.String())

// error

buf.Reset()
l = New(NewJSONHandler(buf), WithCreated(layout), WithLocation(true))
e = newRecord(a, l, LevelWarn)
e = newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(now, l.createdFormat) }
e.With("m1", marshalObject("m1"))
e.With("m2", marshalErrObject("m2"))
e.output()
e.with(l, "m1", marshalObject("m1"))
e.with(l, "m2", marshalErrObject("m2"))
e.output(l.detail, l.handler)
a.Equal(buf.String(), `{"level":"WARN","message":"msg","created":"`+now.Format(layout)+`","path":"path.go:20","attrs":[{"k1":"v1"},{"k2":"v2"},{"m1":"m1"},{"m2":"Err(json: error calling MarshalJSON for type logs.marshalErrObject: marshal json error)"}]}`)
}

Expand All @@ -142,16 +142,16 @@ func TestTermHandler(t *testing.T) {
t.Log("此测试将在终端输出一段带颜色的日志记录")

l := New(nil)
e := newRecord(a, l, LevelWarn)
e := newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(time.Now(), l.createdFormat) }
w := NewTermHandler(os.Stdout, map[Level]colors.Color{LevelError: colors.Green})
w.Handle(e)
w.Handle(l.Detail(), e)

l = New(nil, WithLocation(true), WithCreated(MicroLayout))
e = newRecord(a, l, LevelError)
e = newRecord(a, LevelError)
e.AppendMessage = func(b *Buffer) { b.AppendString("error message") }
w = NewTermHandler(os.Stdout, map[Level]colors.Color{LevelError: colors.Green})
w.Handle(e)
w.Handle(l.Detail(), e)
}

func TestDispatchHandler(t *testing.T) {
Expand All @@ -166,7 +166,7 @@ func TestDispatchHandler(t *testing.T) {
})
l := New(w)

e := l.NewRecord(LevelWarn, l.handler)
e := newRecord(a, LevelWarn)
e.AppendCreated = func(b *Buffer) { b.AppendTime(time.Now(), l.createdFormat) }
l.WARN().Printf("warnf test")
a.Zero(txtBuf.Len()).Contains(jsonBuf.String(), "warnf test").True(json.Valid(jsonBuf.Bytes()))
Expand Down
26 changes: 16 additions & 10 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,42 +31,48 @@ func (l *Logger) AppendAttrs(attrs map[string]any) {
l.h = l.h.WithAttrs(map2Slice(l.logs.printer, attrs))
}

// With 创建 [Recorder] 对象
func (l *Logger) With(name string, val any) Recorder {
if l.IsEnable() {
return l.newRecord().With(name, val)
if !l.IsEnable() {
return disabledRecorder
}
return disabledRecorder

r := withRecordPool.Get().(*withRecorder)
r.logs = l.logs
r.r = l.newRecord().with(l.logs, name, val)
r.h = l.h
return r
}

func (l *Logger) newRecord() *Record { return l.logs.NewRecord(l.lv, l.h) }
func (l *Logger) newRecord() *Record { return NewRecord(l.lv) }

func (l *Logger) Error(err error) {
if l.IsEnable() {
l.newRecord().DepthError(3, err)
l.newRecord().depthError(l.logs, l.h, 3, err)
}
}

func (l *Logger) String(s string) {
if l.IsEnable() {
l.newRecord().DepthString(2, s)
l.newRecord().depthString(l.logs, l.h, 3, s)
}
}

func (l *Logger) Print(v ...any) {
if l.IsEnable() {
l.newRecord().DepthPrint(2, v...)
l.newRecord().depthPrint(l.logs, l.h, 3, v...)
}
}

func (l *Logger) Println(v ...any) {
if l.IsEnable() {
l.newRecord().DepthPrintln(2, v...)
l.newRecord().depthPrintln(l.logs, l.h, 3, v...)
}
}

func (l *Logger) Printf(format string, v ...any) {
if l.IsEnable() {
l.newRecord().DepthPrintf(2, format, v...)
l.newRecord().depthPrintf(l.logs, l.h, 3, format, v...)
}
}

Expand Down Expand Up @@ -96,7 +102,7 @@ func (l *Logger) LogLogger() *log.Logger {
// 仅供 [Logger.LogLogger] 使用,因为 depth 值的关系,只有固定的调用层级关系才能正常显示行号。
func (l *Logger) asWriter() io.Writer {
return writers.WriteFunc(func(data []byte) (int, error) {
l.newRecord().DepthString(5, string(data))
l.newRecord().depthString(l.logs, l.h, 6, string(data))
return len(data), nil
})
}
6 changes: 3 additions & 3 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,22 @@ func TestLogger_location(t *testing.T) {
a.NotNil(l)
l.Enable(LevelError)

// Record.Location
// withRecorder
l.ERROR().With("k1", "v1").
Printf("Record.Printf") // 位置记录此行
val := buf.String()
a.Contains(val, "logger_test.go:22").
Contains(val, "k1=v1").
Contains(val, "Record.Printf")

// Logs.Location
// Logger
buf.Reset()
l.ERROR().Printf("Logs.%s", "Errorf")
val = buf.String()
a.Contains(val, "logger_test.go:30").
Contains(val, "Logs.Errorf")

// logger.Location
// Logger
buf.Reset()
l.ERROR().Print("logger.Print")
val = buf.String()
Expand Down
Loading

0 comments on commit 85a17f8

Please sign in to comment.