| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- package logger
- import (
- "context"
- "strconv"
- "time"
- "git.shuncheng.lu/bigthing/gocommon/pkg/internal/util"
- )
- const (
- TraceIdKey = "trace_id"
- )
- var (
- consoleLogger = util.NewStdOutLogger("[GO-COMMON/LOGGER]", 3)
- )
- // 获取trace_id
- func GetTraceId(ctx context.Context) string {
- if ctx == nil {
- return ""
- }
- value, _ := ctx.Value(TraceIdKey).(string)
- return value
- }
- // 生成trace_id
- func GenerateTraceId() string {
- return strconv.FormatInt(time.Now().UnixNano(), 10)
- }
- // 生产 ctx
- func NewTraceIdContext() context.Context {
- return AddTraceIdContext(context.Background())
- }
- //添加trace_id
- func AddTraceIdContext(ctx context.Context) context.Context {
- if ctx == nil {
- return context.WithValue(context.Background(), TraceIdKey, GenerateTraceId())
- }
- traceId, _ := ctx.Value(TraceIdKey).(string)
- if traceId != "" {
- return ctx
- }
- return context.WithValue(ctx, TraceIdKey, GenerateTraceId())
- }
|