通用包
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
utils/glog/es7/es.go

73 lines
2.0 KiB

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
}