Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ehttp的accessLog支持自定义traceID #370

Merged
merged 1 commit into from
Jan 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -42,14 +44,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
}
Loading