github.com/franciscocpg/up@v0.1.10/platform/event/event.go (about) 1 package event 2 3 import ( 4 "fmt" 5 "strings" 6 "time" 7 8 "github.com/apex/log" 9 ) 10 11 // Events channel. 12 type Events chan *Event 13 14 // Emit an event. 15 func (e Events) Emit(name string, fields Fields) { 16 if !strings.Contains(name, ".event") { 17 log.Debugf("event %s %v", name, fields) 18 } 19 20 e <- &Event{ 21 Name: name, 22 Fields: fields, 23 } 24 } 25 26 // Time an event. 27 func (e Events) Time(name string, fields Fields) func() { 28 start := time.Now() 29 30 e.Emit(name, fields) 31 32 return func() { 33 if fields == nil { 34 fields = make(Fields) 35 } 36 37 f := make(Fields) 38 39 for k, v := range fields { 40 f[k] = v 41 } 42 43 f["duration"] = time.Since(start) 44 e.Emit(name+".complete", f) 45 } 46 } 47 48 // Fields for an event. 49 type Fields map[string]interface{} 50 51 // Event is a representation of an operation performed 52 // by a platform, and is used for reporting. 53 type Event struct { 54 Name string 55 Fields Fields 56 } 57 58 // String value. 59 func (e *Event) String(name string) string { 60 v, ok := e.Fields[name].(string) 61 if !ok { 62 panic(fmt.Errorf("%#v field %s is not a string", e, name)) 63 } 64 return v 65 } 66 67 // Duration value. 68 func (e *Event) Duration(name string) time.Duration { 69 v, ok := e.Fields[name].(time.Duration) 70 if !ok { 71 panic(fmt.Errorf("%#v field %s is not a time.Duration", e, name)) 72 } 73 return v 74 } 75 76 // Int64 value. 77 func (e *Event) Int64(name string) int64 { 78 v, ok := e.Fields[name].(int64) 79 if !ok { 80 panic(fmt.Errorf("%#v field %s is not a int64", e, name)) 81 } 82 return v 83 } 84 85 // Int value. 86 func (e *Event) Int(name string) int { 87 v, ok := e.Fields[name].(int) 88 if !ok { 89 panic(fmt.Errorf("%#v field %s is not a int", e, name)) 90 } 91 return v 92 }