diff --git a/go.mod b/go.mod index a337850..ce9c9a4 100644 --- a/go.mod +++ b/go.mod @@ -7,4 +7,5 @@ require ( github.com/json-iterator/go v1.1.12 github.com/modern-go/reflect2 v1.0.2 golang.org/x/net v0.11.0 + github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b ) diff --git a/tea/tea.go b/tea/tea.go index c984caf..85510a9 100644 --- a/tea/tea.go +++ b/tea/tea.go @@ -26,6 +26,8 @@ import ( "github.com/alibabacloud-go/debug/debug" "github.com/alibabacloud-go/tea/utils" + opentracing "github.com/opentracing/opentracing-go" + "github.com/opentracing/opentracing-go/ext" "golang.org/x/net/proxy" ) @@ -97,6 +99,8 @@ type RuntimeObject struct { Listener utils.ProgressListener `json:"listener" xml:"listener"` Tracker *utils.ReaderTracker `json:"tracker" xml:"tracker"` Logger *utils.Logger `json:"logger" xml:"logger"` + Span opentracing.Span `json:"span" xml:"span"` + IsCloseTrace *bool `json:"isCloseTrace" xml:"isCloseTrace"` } type teaClient struct { @@ -133,6 +137,7 @@ func NewRuntimeObject(runtime map[string]interface{}) *RuntimeObject { Key: TransInterfaceToString(runtime["key"]), Cert: TransInterfaceToString(runtime["cert"]), CA: TransInterfaceToString(runtime["ca"]), + IsCloseTrace: TransInterfaceToBool(runtime["isCloseTrace"]), } if runtime["listener"] != nil { runtimeObject.Listener = runtime["listener"].(utils.ProgressListener) @@ -143,6 +148,9 @@ func NewRuntimeObject(runtime map[string]interface{}) *RuntimeObject { if runtime["logger"] != nil { runtimeObject.Logger = runtime["logger"].(*utils.Logger) } + if runtime["span"] != nil { + runtimeObject.Span = runtime["span"].(opentracing.Span) + } return runtimeObject } @@ -378,6 +386,30 @@ func DoRequest(request *Request, requestRuntime map[string]interface{}) (respons event := utils.NewProgressEvent(utils.TransferStartedEvent, 0, int64(contentlength), 0) utils.PublishProgress(runtimeObject.Listener, event) + // Set tracer + var span opentracing.Span + if ok := opentracing.IsGlobalTracerRegistered(); ok && BoolValue(runtimeObject.IsCloseTrace) != true { + tracer := opentracing.GlobalTracer() + var rootCtx opentracing.SpanContext + var rootSpan opentracing.Span + + if rootSpan = runtimeObject.Span; rootSpan != nil { + rootCtx = rootSpan.Context() + } + + span = tracer.StartSpan( + httpRequest.URL.RequestURI(), + opentracing.ChildOf(rootCtx), + opentracing.Tag{Key: string(ext.Component), Value: "aliyunApi"}, + opentracing.Tag{Key: "request", Value: requestURL}) + + defer span.Finish() + tracer.Inject( + span.Context(), + opentracing.HTTPHeaders, + opentracing.HTTPHeadersCarrier(httpRequest.Header)) + } + putMsgToMap(fieldMap, httpRequest) startTime := time.Now() fieldMap["{start_time}"] = startTime.Format("2006-01-02 15:04:05")