From d12498ed3864762a62fd96dbac55f2d78c33c601 Mon Sep 17 00:00:00 2001 From: "Juan C. Yamacho H" Date: Sun, 1 Jan 2023 13:05:43 +0100 Subject: [PATCH] feat(middleware): redacter interface for logging (#2564) --- middleware/logging/logging.go | 8 ++++++ middleware/logging/logging_test.go | 40 ++++++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/middleware/logging/logging.go b/middleware/logging/logging.go index 6f2922420..9573d1985 100644 --- a/middleware/logging/logging.go +++ b/middleware/logging/logging.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() } diff --git a/middleware/logging/logging_test.go b/middleware/logging/logging_test.go index 431d89014..76cad19b1 100644 --- a/middleware/logging/logging_test.go +++ b/middleware/logging/logging_test.go @@ -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) + } + }) } }