feat(middleware): redacter interface for logging (#2564)

pull/2598/head
Juan C. Yamacho H 2 years ago committed by GitHub
parent 852a77faa6
commit d12498ed38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      middleware/logging/logging.go
  2. 40
      middleware/logging/logging_test.go

@ -11,6 +11,11 @@ import (
"github.com/go-kratos/kratos/v2/transport"
)
// Redacter defines how to log an object
type Redacter interface {
Redact() string
}
// Server is an server logging middleware.
func Server(logger log.Logger) middleware.Middleware {
return func(handler middleware.Handler) middleware.Handler {
@ -85,6 +90,9 @@ func Client(logger log.Logger) middleware.Middleware {
// extractArgs returns the string of the req
func extractArgs(req interface{}) string {
if redacter, ok := req.(Redacter); ok {
return redacter.Redact()
}
if stringer, ok := req.(fmt.Stringer); ok {
return stringer.String()
}

@ -105,19 +105,49 @@ type (
dummyStringer struct {
field string
}
dummyStringerRedacter struct {
field string
}
)
func (d *dummyStringer) String() string {
return "my value"
}
func (d *dummyStringerRedacter) String() string {
return "my value"
}
func (d *dummyStringerRedacter) Redact() string {
return "my value redacted"
}
func TestExtractArgs(t *testing.T) {
if extractArgs(&dummyStringer{field: ""}) != "my value" {
t.Errorf(`The stringified dummyStringer structure must be equal to "my value", %v given`, extractArgs(&dummyStringer{field: ""}))
tests := []struct {
name string
req interface{}
expected string
}{
{
name: "dummyStringer",
req: &dummyStringer{field: ""},
expected: "my value",
}, {
name: "dummy",
req: &dummy{field: "value"},
expected: "&{field:value}",
}, {
name: "dummyStringerRedacter",
req: &dummyStringerRedacter{field: ""},
expected: "my value redacted",
},
}
if extractArgs(&dummy{field: "value"}) != "&{field:value}" {
t.Errorf(`The stringified dummy structure must be equal to "&{field:value}", %v given`, extractArgs(&dummy{field: "value"}))
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if value := extractArgs(test.req); value != test.expected {
t.Errorf(`The stringified %s structure must be equal to "%s", %v given`, test.name, test.expected, value)
}
})
}
}

Loading…
Cancel
Save