From 12410de8d63aa90cf473da18bee001d3bcbff5d9 Mon Sep 17 00:00:00 2001 From: nikkiing <1031497516@qq.com> Date: Fri, 21 Apr 2023 17:01:15 +0800 Subject: [PATCH] =?UTF-8?q?elasticsearch7.10=E6=97=A5=E5=BF=97=E5=92=8Ctra?= =?UTF-8?q?ce?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- glog/es7/es.go | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 glog/es7/es.go diff --git a/glog/es7/es.go b/glog/es7/es.go new file mode 100644 index 0000000..8afe7a3 --- /dev/null +++ b/glog/es7/es.go @@ -0,0 +1,72 @@ +package es7 + +import ( + "bytes" + "context" + "fmt" + "gitea.drugeyes.vip/pharnexbase/utils/glog/v1" + "github.com/elastic/go-elasticsearch/v7/estransport" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + semconv "go.opentelemetry.io/otel/semconv/v1.4.0" + "go.opentelemetry.io/otel/trace" + "net/http" + "time" +) + +var _ estransport.Logger = (*Logger)(nil) + +type Logger struct { + EnableRequestBody bool + EnableResponseBody bool +} + +func (l *Logger) LogRoundTrip(request *http.Request, response *http.Response, err error, time time.Time, duration time.Duration) error { + ctx := request.Context() + index := fmt.Sprintf("%s?%s", request.URL.Path, request.URL.RawQuery) + method := request.Method + if l.RequestBodyEnabled() && request != nil && request.Body != nil && request.Body != http.NoBody { + var buf bytes.Buffer + if request.GetBody != nil { + b, _ := request.GetBody() + _, _ = buf.ReadFrom(b) + } else { + _, _ = buf.ReadFrom(request.Body) + } + glog.Glog.WithContext(ctx).Info("url:", method, index, "request:", buf.String()) + } + + if l.ResponseBodyEnabled() && response != nil && response.Body != nil && response.Body != http.NoBody { + defer response.Body.Close() + var buf bytes.Buffer + _, _ = buf.ReadFrom(response.Body) + glog.Glog.WithContext(ctx).Info("response:", buf.String()) + } + + l.Tracer(ctx, time, method, index) + return nil +} + +func (l *Logger) Tracer(ctx context.Context, begin time.Time, method, index string) { + tracer := otel.Tracer("elasticsearch-v7.10") + kind := trace.SpanKindInternal + + ctx, span := tracer.Start(ctx, + index, + trace.WithSpanKind(kind), + trace.WithTimestamp(begin), + ) + var attrs []attribute.KeyValue + attrs = append(attrs, semconv.DBSystemElasticsearch) + attrs = append(attrs, attribute.Key("es.index").String(method+" "+index)) + span.SetAttributes(attrs...) + span.End(trace.WithTimestamp(time.Now())) +} + +func (l *Logger) RequestBodyEnabled() bool { + return l.EnableRequestBody +} + +func (l *Logger) ResponseBodyEnabled() bool { + return l.EnableResponseBody +}