github.com/gogf/gf@v1.16.9/database/gdb/gdb_core_tracing.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 // 7 8 package gdb 9 10 import ( 11 "context" 12 "fmt" 13 "github.com/gogf/gf" 14 "github.com/gogf/gf/net/gtrace" 15 "go.opentelemetry.io/otel" 16 "go.opentelemetry.io/otel/attribute" 17 "go.opentelemetry.io/otel/codes" 18 "go.opentelemetry.io/otel/trace" 19 ) 20 21 const ( 22 tracingInstrumentName = "github.com/gogf/gf/database/gdb" 23 tracingAttrDbType = "db.type" 24 tracingAttrDbHost = "db.host" 25 tracingAttrDbPort = "db.port" 26 tracingAttrDbName = "db.name" 27 tracingAttrDbUser = "db.user" 28 tracingAttrDbLink = "db.link" 29 tracingAttrDbGroup = "db.group" 30 tracingEventDbExecution = "db.execution" 31 tracingEventDbExecutionSql = "db.execution.sql" 32 tracingEventDbExecutionCost = "db.execution.cost" 33 tracingEventDbExecutionType = "db.execution.type" 34 ) 35 36 // addSqlToTracing adds sql information to tracer if it's enabled. 37 func (c *Core) addSqlToTracing(ctx context.Context, sql *Sql) { 38 if !gtrace.IsTracingInternal() || !gtrace.IsActivated(ctx) { 39 return 40 } 41 tr := otel.GetTracerProvider().Tracer( 42 tracingInstrumentName, 43 trace.WithInstrumentationVersion(gf.VERSION), 44 ) 45 ctx, span := tr.Start(ctx, sql.Type, trace.WithSpanKind(trace.SpanKindInternal)) 46 defer span.End() 47 48 if sql.Error != nil { 49 span.SetStatus(codes.Error, fmt.Sprintf(`%+v`, sql.Error)) 50 } 51 labels := make([]attribute.KeyValue, 0) 52 labels = append(labels, gtrace.CommonLabels()...) 53 labels = append(labels, 54 attribute.String(tracingAttrDbType, c.db.GetConfig().Type), 55 ) 56 if c.db.GetConfig().Host != "" { 57 labels = append(labels, attribute.String(tracingAttrDbHost, c.db.GetConfig().Host)) 58 } 59 if c.db.GetConfig().Port != "" { 60 labels = append(labels, attribute.String(tracingAttrDbPort, c.db.GetConfig().Port)) 61 } 62 if c.db.GetConfig().Name != "" { 63 labels = append(labels, attribute.String(tracingAttrDbName, c.db.GetConfig().Name)) 64 } 65 if c.db.GetConfig().User != "" { 66 labels = append(labels, attribute.String(tracingAttrDbUser, c.db.GetConfig().User)) 67 } 68 if filteredLink := c.db.FilteredLink(); filteredLink != "" { 69 labels = append(labels, attribute.String(tracingAttrDbLink, c.db.FilteredLink())) 70 } 71 if group := c.db.GetGroup(); group != "" { 72 labels = append(labels, attribute.String(tracingAttrDbGroup, group)) 73 } 74 span.SetAttributes(labels...) 75 span.AddEvent(tracingEventDbExecution, trace.WithAttributes( 76 attribute.String(tracingEventDbExecutionSql, sql.Format), 77 attribute.String(tracingEventDbExecutionCost, fmt.Sprintf(`%d ms`, sql.End-sql.Start)), 78 attribute.String(tracingEventDbExecutionType, sql.Type), 79 )) 80 }