diff --git a/log/writer/writer.go b/log/writer/writer.go new file mode 100644 index 00000000..ab62b2fd --- /dev/null +++ b/log/writer/writer.go @@ -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)) +} diff --git a/log/writer/writer_test.go b/log/writer/writer_test.go new file mode 100644 index 00000000..67a28ca0 --- /dev/null +++ b/log/writer/writer_test.go @@ -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]) +}