diff --git a/client/ehttp/interceptor.go b/client/ehttp/interceptor.go index ba9f984c..d71bcff5 100644 --- a/client/ehttp/interceptor.go +++ b/client/ehttp/interceptor.go @@ -2,6 +2,8 @@ package ehttp import ( "context" + "github.com/gotomicro/ego/core/transport" + "github.com/spf13/cast" "log" "net/http" "net/url" @@ -42,7 +44,9 @@ func logAccess(name string, config *Config, logger *elog.Component, req *resty.R } } - var fields = make([]elog.Field, 0, 15) + loggerKeys := transport.CustomContextKeys() + + var fields = make([]elog.Field, 0, 16) fields = append(fields, elog.FieldMethod(fullMethod), elog.FieldName(name), @@ -50,6 +54,13 @@ func logAccess(name string, config *Config, logger *elog.Component, req *resty.R elog.FieldAddr(u.Host), ) + // 支持自定义log + for _, key := range loggerKeys { + if value := transport.Value(req.Context(), key); value != nil { + fields = append(fields, elog.FieldCustomKeyValue(key, cast.ToString(value))) + } + } + // 开启了链路,那么就记录链路id if config.EnableTraceInterceptor && etrace.IsGlobalTracerRegistered() { fields = append(fields, elog.FieldTid(etrace.ExtractTraceID(req.Context()))) diff --git a/examples/http/client/main.go b/examples/http/client/main.go index b183e122..3ffc3861 100644 --- a/examples/http/client/main.go +++ b/examples/http/client/main.go @@ -3,6 +3,7 @@ package main import ( "context" "fmt" + "github.com/gotomicro/ego/core/transport" "github.com/gotomicro/ego" "github.com/gotomicro/ego/client/ehttp" @@ -46,3 +47,20 @@ func callHTTP() error { fmt.Println(info) return nil } + +func callHTTPWithCustomTrace() error { + ctx := context.Background() + + traceID := "123456" + + ctx = transport.WithValue(ctx, "myTraceID", traceID) + + req := httpComp.R() + + info, err := req.SetContext(ctx).SetHeader("x-uid", "101").Get("/hello?aa=bb") + if err != nil { + return err + } + fmt.Println(info) + return nil +}