2020-02-29 03:31:59 +03:00
|
|
|
package logger
|
|
|
|
|
2020-03-26 01:00:43 +03:00
|
|
|
import (
|
2021-07-05 22:32:47 +03:00
|
|
|
"bytes"
|
2021-01-10 18:56:39 +03:00
|
|
|
"context"
|
2020-03-26 01:00:43 +03:00
|
|
|
"testing"
|
|
|
|
)
|
2020-02-29 03:31:59 +03:00
|
|
|
|
|
|
|
func TestLogger(t *testing.T) {
|
2021-01-10 18:56:39 +03:00
|
|
|
ctx := context.TODO()
|
2021-07-05 23:04:20 +03:00
|
|
|
buf := bytes.NewBuffer(nil)
|
|
|
|
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
2020-11-04 00:38:12 +03:00
|
|
|
if err := l.Init(); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
2021-01-10 18:56:39 +03:00
|
|
|
l.Trace(ctx, "trace_msg1")
|
|
|
|
l.Warn(ctx, "warn_msg1")
|
|
|
|
l.Fields(map[string]interface{}{"error": "test"}).Info(ctx, "error message")
|
|
|
|
l.Warn(ctx, "first", " ", "second")
|
2021-07-05 23:04:20 +03:00
|
|
|
if !bytes.Contains(buf.Bytes(), []byte(`"level":"trace","msg":"trace_msg1"`)) {
|
|
|
|
t.Fatalf("logger error, buf %s", buf.Bytes())
|
|
|
|
}
|
|
|
|
if !bytes.Contains(buf.Bytes(), []byte(`"warn","msg":"warn_msg1"`)) {
|
|
|
|
t.Fatalf("logger error, buf %s", buf.Bytes())
|
|
|
|
}
|
|
|
|
if !bytes.Contains(buf.Bytes(), []byte(`"error":"test","level":"info","msg":"error message"`)) {
|
|
|
|
t.Fatalf("logger error, buf %s", buf.Bytes())
|
|
|
|
}
|
|
|
|
if !bytes.Contains(buf.Bytes(), []byte(`"level":"warn","msg":"first second"`)) {
|
|
|
|
t.Fatalf("logger error, buf %s", buf.Bytes())
|
|
|
|
}
|
2020-02-29 03:31:59 +03:00
|
|
|
}
|
2021-07-05 22:32:47 +03:00
|
|
|
|
|
|
|
func TestLoggerWrapper(t *testing.T) {
|
|
|
|
ctx := context.TODO()
|
|
|
|
buf := bytes.NewBuffer(nil)
|
|
|
|
l := NewLogger(WithLevel(TraceLevel), WithOutput(buf))
|
|
|
|
if err := l.Init(WrapLogger(NewOmitWrapper())); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
type secret struct {
|
|
|
|
Name string
|
|
|
|
Passw string `logger:"omit"`
|
|
|
|
}
|
|
|
|
s := &secret{Name: "name", Passw: "secret"}
|
|
|
|
l.Errorf(ctx, "test %#+v", s)
|
|
|
|
if !bytes.Contains(buf.Bytes(), []byte(`logger.secret{Name:\"name\", Passw:\"\"}"`)) {
|
|
|
|
t.Fatalf("omit not works, struct: %v, output: %s", s, buf.Bytes())
|
|
|
|
}
|
|
|
|
}
|
2021-07-05 23:04:20 +03:00
|
|
|
|
|
|
|
func TestOmitLoggerWrapper(t *testing.T) {
|
|
|
|
ctx := context.TODO()
|
|
|
|
buf := bytes.NewBuffer(nil)
|
|
|
|
l := NewOmitLogger(NewLogger(WithLevel(TraceLevel), WithOutput(buf)))
|
|
|
|
if err := l.Init(); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
type secret struct {
|
|
|
|
Name string
|
|
|
|
Passw string `logger:"omit"`
|
|
|
|
}
|
|
|
|
s := &secret{Name: "name", Passw: "secret"}
|
|
|
|
l.Errorf(ctx, "test %#+v", s)
|
|
|
|
if !bytes.Contains(buf.Bytes(), []byte(`logger.secret{Name:\"name\", Passw:\"\"}"`)) {
|
|
|
|
t.Fatalf("omit not works, struct: %v, output: %s", s, buf.Bytes())
|
|
|
|
}
|
|
|
|
}
|