Skip to content

Commit

Permalink
feat(log): Add writer for log (#138)
Browse files Browse the repository at this point in the history
Signed-off-by: Flc゛ <four_leaf_clover@foxmail.com>
  • Loading branch information
flc1125 authored Mar 11, 2024
1 parent b29d67c commit 494bd66
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
23 changes: 23 additions & 0 deletions log/writer/writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package writer

import (
"io"

"github.com/go-kratos/kratos/v2/log"
)

type Writer struct {
logger log.Logger
}

var _ io.Writer = (*Writer)(nil)

func New(logger log.Logger) *Writer {
return &Writer{
logger: logger,
}
}

func (w *Writer) Write(p []byte) (n int, err error) {
return len(p), w.logger.Log(log.LevelInfo, string(p))
}
37 changes: 37 additions & 0 deletions log/writer/writer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package writer

import (
"testing"

"github.com/go-kratos/kratos/v2/log"
"github.com/stretchr/testify/assert"
)

var result = make(chan data, 1)

type data struct {
level log.Level
keyvals []interface{}
}

type logger struct{}

func (l *logger) Log(level log.Level, keyvals ...interface{}) error {
result <- data{
level: level,
keyvals: keyvals,
}
return nil
}

func TestWriter(t *testing.T) {
w := New(&logger{})

n, err := w.Write([]byte("test"))
assert.NoError(t, err)
assert.Equal(t, 4, n)

d := <-result
assert.Equal(t, log.LevelInfo, d.level)
assert.Equal(t, "test", d.keyvals[0])
}

0 comments on commit 494bd66

Please sign in to comment.