Skip to content

Commit

Permalink
Merge pull request #370 from cxlearning/master
Browse files Browse the repository at this point in the history
ehttp的accessLog支持自定义traceID
  • Loading branch information
askuy authored Jan 25, 2024
2 parents 0229a6b + c9f52ef commit d421906
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
13 changes: 12 additions & 1 deletion client/ehttp/interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package ehttp

import (
"context"
"github.com/gotomicro/ego/core/transport"
"github.com/spf13/cast"
"log"
"net/http"
"net/url"
Expand Down Expand Up @@ -44,14 +46,23 @@ 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),
elog.FieldCost(cost),
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())))
Expand Down
18 changes: 18 additions & 0 deletions examples/http/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}

0 comments on commit d421906

Please sign in to comment.