github.com/blend/go-sdk@v1.20220411.3/logger/message_event.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package logger 9 10 import ( 11 "context" 12 "fmt" 13 "io" 14 "time" 15 ) 16 17 // these are compile time assertions 18 var ( 19 _ Event = (*MessageEvent)(nil) 20 ) 21 22 // NewMessageEvent returns a new message event. 23 func NewMessageEvent(flag, text string, options ...MessageEventOption) MessageEvent { 24 me := MessageEvent{ 25 Flag: flag, 26 Text: text, 27 } 28 for _, opt := range options { 29 opt(&me) 30 } 31 return me 32 } 33 34 // NewMessageEventListener returns a new message event listener. 35 func NewMessageEventListener(listener func(context.Context, MessageEvent)) Listener { 36 return func(ctx context.Context, e Event) { 37 if typed, isTyped := e.(MessageEvent); isTyped { 38 listener(ctx, typed) 39 } 40 } 41 } 42 43 // NewMessageEventFilter returns a new message event filter. 44 func NewMessageEventFilter(filter func(context.Context, MessageEvent) (MessageEvent, bool)) Filter { 45 return func(ctx context.Context, e Event) (Event, bool) { 46 if typed, isTyped := e.(MessageEvent); isTyped { 47 return filter(ctx, typed) 48 } 49 return e, false 50 } 51 } 52 53 // MessageEventOption mutates a message event. 54 type MessageEventOption func(*MessageEvent) 55 56 // OptMessageFlag sets a field on a message event. 57 func OptMessageFlag(flag string) MessageEventOption { 58 return func(me *MessageEvent) { me.Flag = flag } 59 } 60 61 // OptMessageText sets a field on a message event. 62 func OptMessageText(text string) MessageEventOption { 63 return func(me *MessageEvent) { me.Text = text } 64 } 65 66 // OptMessageElapsed sets a field on a message event. 67 func OptMessageElapsed(elapsed time.Duration) MessageEventOption { 68 return func(me *MessageEvent) { me.Elapsed = elapsed } 69 } 70 71 // MessageEvent is a common type of message. 72 type MessageEvent struct { 73 Flag string 74 Text string 75 Elapsed time.Duration 76 } 77 78 // GetFlag implements Event. 79 func (e MessageEvent) GetFlag() string { return e.Flag } 80 81 // WriteText implements TextWritable. 82 func (e MessageEvent) WriteText(formatter TextFormatter, output io.Writer) { 83 fmt.Fprint(output, e.Text) 84 if e.Elapsed > 0 { 85 fmt.Fprint(output, Space) 86 fmt.Fprint(output, "("+e.Elapsed.String()+")") 87 } 88 } 89 90 // Decompose implements json.Marshaler. 91 func (e MessageEvent) Decompose() map[string]interface{} { 92 if e.Elapsed > 0 { 93 return map[string]interface{}{ 94 FieldText: e.Text, 95 FieldElapsed: e.Elapsed, 96 } 97 } 98 return map[string]interface{}{ 99 FieldText: e.Text, 100 } 101 }