github.com/orangenpresse/up@v0.6.0/platform/event/event.go (about)

     1  // Package event provides an evented mechanism for hooking into platform specifics.
     2  //
     3  // This is necessary as not all platforms have identical capabilities,
     4  // so the reporting output (among other things) may differ
     5  // slightly.
     6  package event
     7  
     8  import (
     9  	"fmt"
    10  	"strings"
    11  	"time"
    12  
    13  	"github.com/apex/log"
    14  )
    15  
    16  // Events channel.
    17  type Events chan *Event
    18  
    19  // Emit an event.
    20  func (e Events) Emit(name string, fields Fields) {
    21  	if !strings.Contains(name, ".event") {
    22  		log.Debugf("event %s %v", name, fields)
    23  	}
    24  
    25  	e <- &Event{
    26  		Name:   name,
    27  		Fields: fields,
    28  	}
    29  }
    30  
    31  // Time an event.
    32  func (e Events) Time(name string, fields Fields) func() {
    33  	start := time.Now()
    34  
    35  	e.Emit(name, fields)
    36  
    37  	return func() {
    38  		if fields == nil {
    39  			fields = make(Fields)
    40  		}
    41  
    42  		f := make(Fields)
    43  
    44  		for k, v := range fields {
    45  			f[k] = v
    46  		}
    47  
    48  		f["duration"] = time.Since(start)
    49  		e.Emit(name+".complete", f)
    50  	}
    51  }
    52  
    53  // Fields for an event.
    54  type Fields map[string]interface{}
    55  
    56  // Event is a representation of an operation performed
    57  // by a platform, and is used for reporting.
    58  type Event struct {
    59  	Name   string
    60  	Fields Fields
    61  }
    62  
    63  // Strings value.
    64  func (e *Event) Strings(name string) []string {
    65  	v, ok := e.Fields[name].([]string)
    66  	if !ok {
    67  		panic(fmt.Errorf("%#v field %s is not []string", e, name))
    68  	}
    69  	return v
    70  }
    71  
    72  // String value.
    73  func (e *Event) String(name string) string {
    74  	v, ok := e.Fields[name].(string)
    75  	if !ok {
    76  		panic(fmt.Errorf("%#v field %s is not a string", e, name))
    77  	}
    78  	return v
    79  }
    80  
    81  // Duration value.
    82  func (e *Event) Duration(name string) time.Duration {
    83  	v, ok := e.Fields[name].(time.Duration)
    84  	if !ok {
    85  		panic(fmt.Errorf("%#v field %s is not a time.Duration", e, name))
    86  	}
    87  	return v
    88  }
    89  
    90  // Int64 value.
    91  func (e *Event) Int64(name string) int64 {
    92  	v, ok := e.Fields[name].(int64)
    93  	if !ok {
    94  		panic(fmt.Errorf("%#v field %s is not a int64", e, name))
    95  	}
    96  	return v
    97  }
    98  
    99  // Int value.
   100  func (e *Event) Int(name string) int {
   101  	v, ok := e.Fields[name].(int)
   102  	if !ok {
   103  		panic(fmt.Errorf("%#v field %s is not a int", e, name))
   104  	}
   105  	return v
   106  }