github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/log/tapper/log_bd_http_trace.go (about) 1 package tapper 2 3 import ( 4 "context" 5 "strconv" 6 "strings" 7 "time" 8 9 "github.com/gin-gonic/gin" 10 ) 11 12 const ( 13 /* 14 X_bd_caller_uri: 3284,/icourse/main/index,0,0,/icourse,/icourse 15 X_bd_idc: yun 16 X_bd_logid: 32541783 17 X_bd_module: icourse 18 X_bd_product: homework 19 X_bd_spanid: 0.3 20 X_bd_subsys: question 21 X_bd_uniqid: 3528580869 22 X_bd_userip: 183.93.17.119 23 */ 24 25 // 定义spanContext 26 HTTP_KEY_TRACE_ID = "X_bd_logid" 27 HTTP_KEY_SPAN_ID = "X_bd_spanid" // 0.0.0 规则, 此处第一调用为,0.3.0 28 HTTP_KEY_UNIQ_ID = "X_bd_uniqid" 29 HTTP_KEY_CALLER = "X_bd_module" 30 31 HTTP_KEY_IDC = "X_bd_idc" 32 HTTP_KEY_CALLER_URI = "X_bd_caller_uri" //osc 限流,此处不设置 33 HTTP_KEY_SUBSYS = "X_bd_subsys" 34 35 // 自定义baggage,需全程透传 36 HTTP_KEY_PRODUCT = "X_bd_product" 37 HTTP_KEY_USERIP = "X_bd_userip" 38 39 HTTP_USER_AGENT = "User-Agent" 40 ) 41 42 var Project = "" 43 var _USER_AGENT = "ral/go " 44 45 type BDTraceLog struct { 46 } 47 48 // 生成logId 49 func GenLogId() string { 50 now := time.Now() 51 logId := ((now.UnixNano()*1e5 + now.UnixNano()/1e7) & 0x7FFFFFFF) | 0x80000000 52 return strconv.FormatInt(logId, 10) 53 } 54 55 func (l *BDTraceLog) SetTraceLogFromGinHeader(c *gin.Context) *TraceLog { 56 traceLog := &TraceLog{} 57 //获取当前LogId 58 bdLogId := c.GetHeader(HTTP_KEY_TRACE_ID) 59 if bdLogId != "" && bdLogId != "0" { 60 traceLog.LogId = strings.TrimSpace(bdLogId) 61 } else { 62 traceLog.LogId = GenLogId() 63 } 64 //获取调用者 65 traceLog.Caller = c.GetHeader(HTTP_KEY_CALLER) 66 //获取调用者refer 67 //traceLog.Refer = c.GetHeader(HTTP_KEY_CALLER_URI) 68 //调用userip 69 traceLog.UniqId = c.GetHeader(HTTP_KEY_UNIQ_ID) 70 //获取当前的调用接口路径 71 traceLog.Path = c.Request.URL.Path 72 73 //设置mq的请求transid 74 traceLog.MqTransId = c.Query("transid") 75 76 //全程透传 77 traceLog.UserIP = c.GetHeader(HTTP_KEY_USERIP) 78 traceLog.Product = c.GetHeader(HTTP_KEY_PRODUCT) 79 c.Set(TRACECTX, traceLog) 80 return traceLog 81 } 82 83 func SetTraceHeaderByGinContext(ctx context.Context, header map[string]string) map[string]string { 84 if header == nil { 85 header = make(map[string]string) 86 } 87 traceLog, _ := GetTraceLogFromGinContext(ctx) 88 89 header[HTTP_KEY_TRACE_ID] = traceLog.LogId 90 header[HTTP_KEY_SPAN_ID] = traceLog.GetCurrentSpanId() 91 header[HTTP_KEY_UNIQ_ID] = traceLog.UniqId 92 header[HTTP_KEY_CALLER] = Project //注册Log时服务名称 93 //header[HTTP_KEY_CALLER_URI] = traceLog.Path //当前的api接口 94 95 header[HTTP_KEY_PRODUCT] = traceLog.Product 96 header[HTTP_KEY_USERIP] = traceLog.UserIP 97 98 //设置本应用请求时设置header头,保持链路 99 header[HTTP_USER_AGENT] = _USER_AGENT + Project 100 return header 101 }