From ae09d0e56d2422811d8b714f1acb11ea0c2ec843 Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Wed, 29 Jan 2025 00:32:21 +0800 Subject: [PATCH] chore: use logc instead of logx if possible (#4610) --- core/discov/internal/registry.go | 14 +++++++------- core/discov/internal/registry_test.go | 2 +- core/discov/publisher.go | 13 +++++++------ rest/handler/authhandler.go | 4 ++-- rest/handler/breakerhandler.go | 4 ++-- rest/handler/contentsecurityhandler.go | 6 +++--- rest/handler/cryptionhandler.go | 11 ++++++----- rest/handler/cryptionhandler_test.go | 7 ++++--- rest/handler/sheddinghandler.go | 4 ++-- rest/httpx/responses.go | 3 ++- rest/internal/security/contentsecurity.go | 4 ++-- .../serverinterceptors/recoverinterceptor.go | 10 +++++----- 12 files changed, 43 insertions(+), 39 deletions(-) diff --git a/core/discov/internal/registry.go b/core/discov/internal/registry.go index f440adc3c40a..49463f7bcc92 100644 --- a/core/discov/internal/registry.go +++ b/core/discov/internal/registry.go @@ -11,7 +11,7 @@ import ( "time" "github.com/zeromicro/go-zero/core/lang" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/mathx" "github.com/zeromicro/go-zero/core/syncx" "github.com/zeromicro/go-zero/core/threading" @@ -249,7 +249,7 @@ func (c *cluster) handleChanges(key watchKey, kvs []KV) { } } -func (c *cluster) handleWatchEvents(key watchKey, events []*clientv3.Event) { +func (c *cluster) handleWatchEvents(ctx context.Context, key watchKey, events []*clientv3.Event) { c.lock.RLock() watcher, ok := c.watchers[key] if !ok { @@ -283,7 +283,7 @@ func (c *cluster) handleWatchEvents(key watchKey, events []*clientv3.Event) { }) } default: - logx.Errorf("Unknown event type: %v", ev.Type) + logc.Errorf(ctx, "Unknown event type: %v", ev.Type) } } } @@ -304,7 +304,7 @@ func (c *cluster) load(cli EtcdClient, key watchKey) int64 { break } - logx.Errorf("%s, key: %s, exactMatch: %t", err.Error(), key.key, key.exactMatch) + logc.Errorf(cli.Ctx(), "%s, key: %s, exactMatch: %t", err.Error(), key.key, key.exactMatch) time.Sleep(coolDownUnstable.AroundDuration(coolDownInterval)) } @@ -382,12 +382,12 @@ func (c *cluster) watch(cli EtcdClient, key watchKey, rev int64) { } if rev != 0 && errors.Is(err, rpctypes.ErrCompacted) { - logx.Errorf("etcd watch stream has been compacted, try to reload, rev %d", rev) + logc.Errorf(cli.Ctx(), "etcd watch stream has been compacted, try to reload, rev %d", rev) rev = c.load(cli, key) } // log the error and retry - logx.Error(err) + logc.Error(cli.Ctx(), err) } } @@ -407,7 +407,7 @@ func (c *cluster) watchStream(cli EtcdClient, key watchKey, rev int64) error { return fmt.Errorf("etcd monitor chan error: %w", wresp.Err()) } - c.handleWatchEvents(key, wresp.Events) + c.handleWatchEvents(ctx, key, wresp.Events) case <-ctx.Done(): return nil case <-c.done: diff --git a/core/discov/internal/registry_test.go b/core/discov/internal/registry_test.go index 2f933364d1b9..7a324325604b 100644 --- a/core/discov/internal/registry_test.go +++ b/core/discov/internal/registry_test.go @@ -300,7 +300,7 @@ func TestCluster_handleWatchEvents(t *testing.T) { }, } assert.NotPanics(t, func() { - c.handleWatchEvents(watchKey{ + c.handleWatchEvents(context.Background(), watchKey{ key: "another", }, nil) }) diff --git a/core/discov/publisher.go b/core/discov/publisher.go index 6d84201298ea..03f23a52d60f 100644 --- a/core/discov/publisher.go +++ b/core/discov/publisher.go @@ -5,6 +5,7 @@ import ( "github.com/zeromicro/go-zero/core/discov/internal" "github.com/zeromicro/go-zero/core/lang" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/proc" "github.com/zeromicro/go-zero/core/syncx" @@ -91,12 +92,12 @@ func (p *Publisher) doKeepAlive() error { default: cli, err := p.doRegister() if err != nil { - logx.Errorf("etcd publisher doRegister: %s", err.Error()) + logc.Errorf(cli.Ctx(), "etcd publisher doRegister: %s", err.Error()) break } if err := p.keepAliveAsync(cli); err != nil { - logx.Errorf("etcd publisher keepAliveAsync: %s", err.Error()) + logc.Errorf(cli.Ctx(), "etcd publisher keepAliveAsync: %s", err.Error()) break } @@ -130,17 +131,17 @@ func (p *Publisher) keepAliveAsync(cli internal.EtcdClient) error { if !ok { p.revoke(cli) if err := p.doKeepAlive(); err != nil { - logx.Errorf("etcd publisher KeepAlive: %s", err.Error()) + logc.Errorf(cli.Ctx(), "etcd publisher KeepAlive: %s", err.Error()) } return } case <-p.pauseChan: - logx.Infof("paused etcd renew, key: %s, value: %s", p.key, p.value) + logc.Infof(cli.Ctx(), "paused etcd renew, key: %s, value: %s", p.key, p.value) p.revoke(cli) select { case <-p.resumeChan: if err := p.doKeepAlive(); err != nil { - logx.Errorf("etcd publisher KeepAlive: %s", err.Error()) + logc.Errorf(cli.Ctx(), "etcd publisher KeepAlive: %s", err.Error()) } return case <-p.quit.Done(): @@ -175,7 +176,7 @@ func (p *Publisher) register(client internal.EtcdClient) (clientv3.LeaseID, erro func (p *Publisher) revoke(cli internal.EtcdClient) { if _, err := cli.Revoke(cli.Ctx(), p.lease); err != nil { - logx.Errorf("etcd publisher revoke: %s", err.Error()) + logc.Errorf(cli.Ctx(), "etcd publisher revoke: %s", err.Error()) } } diff --git a/rest/handler/authhandler.go b/rest/handler/authhandler.go index f72e2113a96f..ab781bbfa2a9 100644 --- a/rest/handler/authhandler.go +++ b/rest/handler/authhandler.go @@ -7,7 +7,7 @@ import ( "net/http/httputil" "github.com/golang-jwt/jwt/v4" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/rest/internal/response" "github.com/zeromicro/go-zero/rest/token" ) @@ -100,7 +100,7 @@ func WithUnauthorizedCallback(callback UnauthorizedCallback) AuthorizeOption { func detailAuthLog(r *http.Request, reason string) { // discard dump error, only for debug purpose details, _ := httputil.DumpRequest(r, true) - logx.Errorf("authorize failed: %s\n=> %+v", reason, string(details)) + logc.Errorf(r.Context(), "authorize failed: %s\n=> %+v", reason, string(details)) } func unauthorized(w http.ResponseWriter, r *http.Request, err error, callback UnauthorizedCallback) { diff --git a/rest/handler/breakerhandler.go b/rest/handler/breakerhandler.go index 05b85bc8d9a4..affa6010455e 100644 --- a/rest/handler/breakerhandler.go +++ b/rest/handler/breakerhandler.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/zeromicro/go-zero/core/breaker" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/response" @@ -22,7 +22,7 @@ func BreakerHandler(method, path string, metrics *stat.Metrics) func(http.Handle promise, err := brk.Allow() if err != nil { metrics.AddDrop() - logx.Errorf("[http] dropped, %s - %s - %s", + logc.Errorf(r.Context(), "[http] dropped, %s - %s - %s", r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent()) w.WriteHeader(http.StatusServiceUnavailable) return diff --git a/rest/handler/contentsecurityhandler.go b/rest/handler/contentsecurityhandler.go index bd095fe97476..11da9ff6ca56 100644 --- a/rest/handler/contentsecurityhandler.go +++ b/rest/handler/contentsecurityhandler.go @@ -5,7 +5,7 @@ import ( "time" "github.com/zeromicro/go-zero/core/codec" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/security" ) @@ -34,11 +34,11 @@ func LimitContentSecurityHandler(limitBytes int64, decrypters map[string]codec.R case http.MethodDelete, http.MethodGet, http.MethodPost, http.MethodPut: header, err := security.ParseContentSecurity(decrypters, r) if err != nil { - logx.Errorf("Signature parse failed, X-Content-Security: %s, error: %s", + logc.Errorf(r.Context(), "Signature parse failed, X-Content-Security: %s, error: %s", r.Header.Get(contentSecurity), err.Error()) executeCallbacks(w, r, next, strict, httpx.CodeSignatureInvalidHeader, callbacks) } else if code := security.VerifySignature(r, header, tolerance); code != httpx.CodeSignaturePass { - logx.Errorf("Signature verification failed, X-Content-Security: %s", + logc.Errorf(r.Context(), "Signature verification failed, X-Content-Security: %s", r.Header.Get(contentSecurity)) executeCallbacks(w, r, next, strict, code, callbacks) } else if r.ContentLength > 0 && header.Encrypted() { diff --git a/rest/handler/cryptionhandler.go b/rest/handler/cryptionhandler.go index 18ba85b326c8..88832a40542b 100644 --- a/rest/handler/cryptionhandler.go +++ b/rest/handler/cryptionhandler.go @@ -3,6 +3,7 @@ package handler import ( "bufio" "bytes" + "context" "encoding/base64" "errors" "io" @@ -10,7 +11,7 @@ import ( "net/http" "github.com/zeromicro/go-zero/core/codec" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logc" ) const maxBytes = 1 << 20 // 1 MiB @@ -27,7 +28,7 @@ func LimitCryptionHandler(limitBytes int64, key []byte) func(http.Handler) http. return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cw := newCryptionResponseWriter(w) - defer cw.flush(key) + defer cw.flush(r.Context(), key) if r.ContentLength <= 0 { next.ServeHTTP(cw, r) @@ -118,7 +119,7 @@ func (w *cryptionResponseWriter) WriteHeader(statusCode int) { w.ResponseWriter.WriteHeader(statusCode) } -func (w *cryptionResponseWriter) flush(key []byte) { +func (w *cryptionResponseWriter) flush(ctx context.Context, key []byte) { if w.buf.Len() == 0 { return } @@ -131,8 +132,8 @@ func (w *cryptionResponseWriter) flush(key []byte) { body := base64.StdEncoding.EncodeToString(content) if n, err := io.WriteString(w.ResponseWriter, body); err != nil { - logx.Errorf("write response failed, error: %s", err) + logc.Errorf(ctx, "write response failed, error: %s", err) } else if n < len(body) { - logx.Errorf("actual bytes: %d, written bytes: %d", len(body), n) + logc.Errorf(ctx, "actual bytes: %d, written bytes: %d", len(body), n) } } diff --git a/rest/handler/cryptionhandler_test.go b/rest/handler/cryptionhandler_test.go index f993cac58151..1d350bc3b816 100644 --- a/rest/handler/cryptionhandler_test.go +++ b/rest/handler/cryptionhandler_test.go @@ -2,6 +2,7 @@ package handler import ( "bytes" + "context" "crypto/rand" "encoding/base64" "io" @@ -174,7 +175,7 @@ func TestCryptionResponseWriter_Flush(t *testing.T) { w := newCryptionResponseWriter(f) _, err := w.Write(body) assert.NoError(t, err) - w.flush(aesKey) + w.flush(context.Background(), aesKey) b, err := io.ReadAll(recorder.Body) assert.NoError(t, err) expected, err := codec.EcbEncrypt(aesKey, body) @@ -191,7 +192,7 @@ func TestCryptionResponseWriter_Flush(t *testing.T) { w := newCryptionResponseWriter(f) _, err := w.Write(body) assert.NoError(t, err) - w.flush(aesKey) + w.flush(context.Background(), aesKey) b, err := io.ReadAll(recorder.Body) assert.NoError(t, err) expected, err := codec.EcbEncrypt(aesKey, body) @@ -207,7 +208,7 @@ func TestCryptionResponseWriter_Flush(t *testing.T) { w := newCryptionResponseWriter(f) _, err := w.Write(body) assert.NoError(t, err) - w.flush(aesKey) + w.flush(context.Background(), aesKey) assert.True(t, strings.Contains(buf.Content(), io.ErrClosedPipe.Error())) }) } diff --git a/rest/handler/sheddinghandler.go b/rest/handler/sheddinghandler.go index 80cfe12246d3..cbe41e7725d8 100644 --- a/rest/handler/sheddinghandler.go +++ b/rest/handler/sheddinghandler.go @@ -5,7 +5,7 @@ import ( "sync" "github.com/zeromicro/go-zero/core/load" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/response" @@ -35,7 +35,7 @@ func SheddingHandler(shedder load.Shedder, metrics *stat.Metrics) func(http.Hand if err != nil { metrics.AddDrop() sheddingStat.IncrementDrop() - logx.Errorf("[http] dropped, %s - %s - %s", + logc.Errorf(r.Context(), "[http] dropped, %s - %s - %s", r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent()) w.WriteHeader(http.StatusServiceUnavailable) return diff --git a/rest/httpx/responses.go b/rest/httpx/responses.go index 9c3d442914af..40995cc7e74e 100644 --- a/rest/httpx/responses.go +++ b/rest/httpx/responses.go @@ -9,6 +9,7 @@ import ( "net/http" "sync" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/internal/errcode" "github.com/zeromicro/go-zero/rest/internal/header" @@ -119,7 +120,7 @@ func WriteJson(w http.ResponseWriter, code int, v any) { // WriteJsonCtx writes v as json string into w with code. func WriteJsonCtx(ctx context.Context, w http.ResponseWriter, code int, v any) { if err := doWriteJson(w, code, v); err != nil { - logx.WithContext(ctx).Error(err) + logc.Error(ctx, err) } } diff --git a/rest/internal/security/contentsecurity.go b/rest/internal/security/contentsecurity.go index 5e3bbb02d6ba..c580c88c0508 100644 --- a/rest/internal/security/contentsecurity.go +++ b/rest/internal/security/contentsecurity.go @@ -14,7 +14,7 @@ import ( "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/core/iox" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/rest/httpx" ) @@ -123,7 +123,7 @@ func VerifySignature(r *http.Request, securityHeader *ContentSecurityHeader, tol return httpx.CodeSignaturePass } - logx.Infof("signature different, expect: %s, actual: %s", + logc.Infof(r.Context(), "signature different, expect: %s, actual: %s", securityHeader.Signature, actualSignature) return httpx.CodeSignatureInvalidToken diff --git a/zrpc/internal/serverinterceptors/recoverinterceptor.go b/zrpc/internal/serverinterceptors/recoverinterceptor.go index 84c4632a1599..8e5afda44060 100644 --- a/zrpc/internal/serverinterceptors/recoverinterceptor.go +++ b/zrpc/internal/serverinterceptors/recoverinterceptor.go @@ -4,7 +4,7 @@ import ( "context" "runtime/debug" - "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/core/logc" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -14,7 +14,7 @@ import ( func StreamRecoverInterceptor(svr any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { defer handleCrash(func(r any) { - err = toPanicError(r) + err = toPanicError(context.Background(), r) }) return handler(svr, stream) @@ -24,7 +24,7 @@ func StreamRecoverInterceptor(svr any, stream grpc.ServerStream, _ *grpc.StreamS func UnaryRecoverInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { defer handleCrash(func(r any) { - err = toPanicError(r) + err = toPanicError(ctx, r) }) return handler(ctx, req) @@ -36,7 +36,7 @@ func handleCrash(handler func(any)) { } } -func toPanicError(r any) error { - logx.Errorf("%+v\n\n%s", r, debug.Stack()) +func toPanicError(ctx context.Context, r any) error { + logc.Errorf(ctx, "%+v\n\n%s", r, debug.Stack()) return status.Errorf(codes.Internal, "panic: %v", r) }