context.go 1.93 KB
Newer Older
chenweijian's avatar
chenweijian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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,
	})
}