package mycontext import ( "context" uuid "github.com/satori/go.uuid" "github.com/sirupsen/logrus" "hilo-user/_const" "hilo-user/mylogrus" "strconv" "strings" ) /** * 主要是完成日志打印 * @param * @return **/ type MyContext struct { context.Context Log *logrus.Entry Cxt map[string]interface{} } func CreateMyContextWith(traceId interface{}) *MyContext { cxt := map[string]interface{}{} cxt[_const.TRACEID] = traceId return CreateMyContext(cxt) } func CreateMyContext(ctx map[string]interface{}) *MyContext { var traceId string if traceIdTemp, ok := ctx[_const.TRACEID]; ok { traceId, ok = traceIdTemp.(string) } else { traceId = strings.Replace(uuid.NewV4().String(), "-", "", -1) } var userId string if userIdTemp, ok := ctx[_const.USERID]; ok { userId = strconv.FormatUint(userIdTemp.(uint64), 10) } var deviceTypeStr string if deviceTypeTemp, ok := ctx[_const.DEVICETYPE]; ok { deviceTypeStr, ok = deviceTypeTemp.(string) } var sAppVersion string if appVersionTmp, ok := ctx[_const.APP_VERSION]; ok { sAppVersion, ok = appVersionTmp.(string) } var url string if urlTmp, ok := ctx[_const.URL]; ok { url, ok = urlTmp.(string) } var method string if methodTmp, ok := ctx[_const.METHOD]; ok { method, ok = methodTmp.(string) } _ctx := context.WithValue(context.Background(), "traceId", traceId) _ctx = context.WithValue(_ctx, "userId", userId) return &MyContext{ Context: _ctx, Log: CreateContextLog(userId, traceId, deviceTypeStr, sAppVersion, url, method), Cxt: ctx, } } /** * 创建上下文的日志 **/ func CreateContextLog(userId string, traceId string, deviceType string, deviceVersion string, url string, method string) *logrus.Entry { return mylogrus.MyLog.WithFields(logrus.Fields{ _const.USERID: userId, _const.TRACEID: traceId, _const.DEVICETYPE: deviceType, _const.APP_VERSION: deviceVersion, _const.URL: url, _const.METHOD: method, }) }