Skip to content

Commit

Permalink
chore: use logc instead of logx if possible (#4610)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan authored Jan 28, 2025
1 parent 0bc4206 commit ae09d0e
Show file tree
Hide file tree
Showing 12 changed files with 43 additions and 39 deletions.
14 changes: 7 additions & 7 deletions core/discov/internal/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
}
}
Expand All @@ -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))
}

Expand Down Expand Up @@ -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)
}
}

Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion core/discov/internal/registry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down
13 changes: 7 additions & 6 deletions core/discov/publisher.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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())
}
}

Expand Down
4 changes: 2 additions & 2 deletions rest/handler/authhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions rest/handler/breakerhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions rest/handler/contentsecurityhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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() {
Expand Down
11 changes: 6 additions & 5 deletions rest/handler/cryptionhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package handler
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"errors"
"io"
"net"
"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
Expand All @@ -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)
Expand Down Expand Up @@ -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
}
Expand All @@ -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)
}
}
7 changes: 4 additions & 3 deletions rest/handler/cryptionhandler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package handler

import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"io"
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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()))
})
}
Expand Down
4 changes: 2 additions & 2 deletions rest/handler/sheddinghandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion rest/httpx/responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
}
}

Expand Down
4 changes: 2 additions & 2 deletions rest/internal/security/contentsecurity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions zrpc/internal/serverinterceptors/recoverinterceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
}

0 comments on commit ae09d0e

Please sign in to comment.