trace/trace.go

95 lines
2.1 KiB
Go
Raw Normal View History

2022-10-15 00:08:32 +08:00
// 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
2022-10-15 00:23:50 +08:00
behaviorList []Behavior // 行为列表
2022-10-15 00:08:32 +08:00
}
// 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()
2022-10-15 00:23:50 +08:00
b := Behavior{
2022-10-15 00:08:32 +08:00
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
2022-10-15 00:23:50 +08:00
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)
}
2022-10-15 00:08:32 +08:00
2022-10-15 00:23:50 +08:00
// 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)
2022-10-15 00:08:32 +08:00
}