github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/log/tapper/monitor_ctx.go (about)

     1  package tapper
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"sync"
     7  
     8  	hack "github.com/weedge/lib/strings"
     9  
    10  	"github.com/gin-gonic/gin"
    11  	jsoniter "github.com/json-iterator/go"
    12  )
    13  
    14  const (
    15  	MONITORCTX = "MONITORCTX"
    16  )
    17  
    18  type Monitor struct {
    19  	data map[string]interface{}
    20  	mu   sync.Mutex
    21  }
    22  
    23  func (monitor *Monitor) Marshal() string {
    24  	monitor.mu.Lock()
    25  	defer monitor.mu.Unlock()
    26  
    27  	b, _ := jsoniter.MarshalToString(monitor.data)
    28  	return b
    29  }
    30  func (monitor *Monitor) Push(args ...interface{}) *Monitor {
    31  	monitor.mu.Lock()
    32  	defer monitor.mu.Unlock()
    33  
    34  	for i := 0; i < len(args)-1; i += 2 {
    35  		switch args[i+1].(type) {
    36  		case string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
    37  			monitor.data[fmt.Sprintf("%v", args[i])] = args[i+1]
    38  		default:
    39  			if b, e := jsoniter.Marshal(args[i+1]); e == nil {
    40  				monitor.data[fmt.Sprintf("%v", args[i])] = hack.String(b)
    41  			}
    42  		}
    43  	}
    44  	return monitor
    45  }
    46  
    47  func GetMonitorFromContext(ctx context.Context) (context.Context, *Monitor) {
    48  	switch c := ctx.(type) {
    49  	case *gin.Context:
    50  		if monitor, ok := c.Get(MONITORCTX); ok && monitor != nil {
    51  			if monitor, ok := monitor.(*Monitor); ok && monitor != nil {
    52  				return ctx, monitor
    53  			}
    54  		}
    55  
    56  		monitor := &Monitor{data: map[string]interface{}{}}
    57  		c.Set(MONITORCTX, monitor)
    58  		return ctx, monitor
    59  
    60  	case nil:
    61  	default:
    62  	}
    63  
    64  	monitor := &Monitor{data: map[string]interface{}{}}
    65  	return ctx, monitor
    66  }
    67  
    68  // 参数args: [key value]...
    69  func PushMonitor(ctx context.Context, args ...interface{}) {
    70  	ctx, monitor := GetMonitorFromContext(ctx)
    71  	monitor.Push(args...)
    72  }