util.go 919 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package logger
  2. import (
  3. "context"
  4. "strconv"
  5. "time"
  6. "git.shuncheng.lu/bigthing/gocommon/pkg/internal/util"
  7. )
  8. const (
  9. TraceIdKey = "trace_id"
  10. )
  11. var (
  12. consoleLogger = util.NewStdOutLogger("[GO-COMMON/LOGGER]", 3)
  13. )
  14. // 获取trace_id
  15. func GetTraceId(ctx context.Context) string {
  16. if ctx == nil {
  17. return ""
  18. }
  19. value, _ := ctx.Value(TraceIdKey).(string)
  20. return value
  21. }
  22. // 生成trace_id
  23. func GenerateTraceId() string {
  24. return strconv.FormatInt(time.Now().UnixNano(), 10)
  25. }
  26. // 生产 ctx
  27. func NewTraceIdContext() context.Context {
  28. return AddTraceIdContext(context.Background())
  29. }
  30. //添加trace_id
  31. func AddTraceIdContext(ctx context.Context) context.Context {
  32. if ctx == nil {
  33. return context.WithValue(context.Background(), TraceIdKey, GenerateTraceId())
  34. }
  35. traceId, _ := ctx.Value(TraceIdKey).(string)
  36. if traceId != "" {
  37. return ctx
  38. }
  39. return context.WithValue(ctx, TraceIdKey, GenerateTraceId())
  40. }