github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/catgo/cat-go/message/transaction.go (about) 1 package message 2 3 import ( 4 "sync" 5 "time" 6 ) 7 8 type TransactionGetter interface { 9 GetDuration() time.Duration 10 } 11 12 type Transactor interface { 13 Messager 14 TransactionGetter 15 SetDuration(duration time.Duration) 16 SetDurationStart(time time.Time) 17 NewEvent(mtype, name string) Messager 18 LogEvent(mtype, name string, args ...string) 19 } 20 21 type Transaction struct { 22 Message 23 24 children []Messager 25 26 isCompleted bool 27 28 mu sync.Mutex 29 30 duration time.Duration 31 durationStart time.Time 32 } 33 34 func (t *Transaction) Complete() { 35 if t.isCompleted { 36 return 37 } 38 t.isCompleted = true 39 40 if t.duration == 0 { 41 t.duration = time.Now().Sub(t.Message.timestamp) 42 } 43 44 if t.Message.flush != nil { 45 t.Message.flush(t) 46 } 47 } 48 49 func (t *Transaction) GetDuration() time.Duration { 50 return t.duration 51 } 52 53 func (t *Transaction) SetDuration(duration time.Duration) { 54 t.duration = duration 55 } 56 func (t *Transaction) SetDurationStart(time time.Time) { 57 t.durationStart = time 58 } 59 60 func (t *Transaction) NewEvent(mtype, name string) Messager { 61 var e = NewEvent(mtype, name, nil) 62 t.AddChild(e) 63 return e 64 } 65 66 func (t *Transaction) LogEvent(mtype, name string, args ...string) { 67 var e = t.NewEvent(mtype, name) 68 if len(args) > 0 { 69 e.SetStatus(args[0]) 70 } 71 if len(args) > 1 { 72 e.SetData(args[1]) 73 } 74 e.Complete() 75 } 76 77 func (t *Transaction) AddChild(m Messager) { 78 t.mu.Lock() 79 defer t.mu.Unlock() 80 t.children = append(t.children, m) 81 } 82 83 func (t *Transaction) GetChildren() []Messager { 84 return t.children 85 } 86 87 func NewTransaction(mtype, name string, flush Flush) *Transaction { 88 return &Transaction{ 89 Message: NewMessage(mtype, name, flush), 90 children: make([]Messager, 0), 91 isCompleted: false, 92 mu: sync.Mutex{}, 93 duration: 0, 94 durationStart: time.Time{}, 95 } 96 }