95 lines
2.1 KiB
Go
95 lines
2.1 KiB
Go
// Package trace ...
|
|
//
|
|
// Description : trace ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2022-10-14 23:25
|
|
package trace
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// NewRuntime 获取runtime实例
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 23:26 2022/10/14
|
|
func NewRuntime(traceID string) *Runtime {
|
|
return &Runtime{
|
|
lock: &sync.Mutex{},
|
|
traceID: traceID,
|
|
behaviorList: make([]Behavior, 0),
|
|
}
|
|
}
|
|
|
|
// Runtime ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 23:32 2022/10/14
|
|
type Runtime struct {
|
|
lock *sync.Mutex // 锁
|
|
traceID string // 日志追踪ID
|
|
behaviorList []Behavior // 行为列表
|
|
}
|
|
|
|
// StartBehavior 开始一个行为
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 23:41 2022/10/14
|
|
func (r *Runtime) StartBehavior(action string, data map[string]interface{}) int {
|
|
if nil == data {
|
|
data = make(map[string]interface{})
|
|
}
|
|
r.lock.Lock()
|
|
defer r.lock.Unlock()
|
|
b := Behavior{
|
|
ID: len(r.behaviorList),
|
|
Action: action,
|
|
Type: BehaviorActionTypeStart,
|
|
Timestamp: time.Now().UnixNano(),
|
|
Data: data,
|
|
}
|
|
r.behaviorList = append(r.behaviorList, b)
|
|
return b.ID
|
|
}
|
|
|
|
// FinishBehavior 结束某一个行为
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 23:53 2022/10/14
|
|
func (r *Runtime) FinishBehavior(behaviorID int, data map[string]interface{}) {
|
|
if nil == data {
|
|
data = make(map[string]interface{})
|
|
}
|
|
r.lock.Lock()
|
|
defer r.lock.Unlock()
|
|
b := Behavior{
|
|
ID: len(r.behaviorList),
|
|
StartBehaviorID: behaviorID,
|
|
Action: r.behaviorList[behaviorID].Action,
|
|
Type: BehaviorActionTypeFinish,
|
|
Timestamp: time.Now().UnixNano(),
|
|
Data: data,
|
|
}
|
|
r.behaviorList = append(r.behaviorList, b)
|
|
}
|
|
|
|
// WrapRun ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 00:17 2022/10/15
|
|
func (r *Runtime) WrapRun(action string, startData map[string]interface{}, logic func()) {
|
|
if nil == logic {
|
|
return
|
|
}
|
|
behaviorID := r.StartBehavior(action, startData)
|
|
defer r.FinishBehavior(behaviorID, nil)
|
|
}
|