github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/countlog/output/writer.go (about) 1 package output 2 3 import ( 4 "github.com/v2pro/plz/countlog/spi" 5 "io" 6 "sync" 7 "os" 8 "github.com/v2pro/plz/countlog/loglog" 9 ) 10 11 type EventWriter struct { 12 format Format 13 writer io.Writer 14 } 15 16 type EventWriterConfig struct { 17 Format Format 18 Writer io.Writer 19 } 20 21 func NewEventWriter(cfg EventWriterConfig) *EventWriter { 22 writer := cfg.Writer 23 if writer == nil { 24 writer = os.Stdout 25 } 26 writer = &recylceWriter{writer} 27 return &EventWriter{ 28 format: cfg.Format, 29 writer: writer, 30 } 31 } 32 33 func (sink *EventWriter) HandlerOf(site *spi.LogSite) spi.EventHandler { 34 formatter := sink.format.FormatterOf(site) 35 return &writeEvent{ 36 site: site, 37 formatter: formatter, 38 writer: sink.writer, 39 } 40 } 41 42 type writeEvent struct { 43 site *spi.LogSite 44 formatter Formatter 45 writer io.Writer 46 } 47 48 func (handler *writeEvent) Handle(event *spi.Event) { 49 space := bufPool.Get().([]byte)[:0] 50 formatted := handler.formatter.Format(space, event) 51 _, err := handler.writer.Write(formatted) 52 if err != nil { 53 loglog.Error(err) 54 } 55 } 56 57 func (handler *writeEvent) LogSite() *spi.LogSite { 58 return handler.site 59 } 60 61 var bufPool = &sync.Pool{ 62 New: func() interface{} { 63 return make([]byte, 0, 128) 64 }, 65 } 66 67 type recylceWriter struct { 68 writer io.Writer 69 } 70 71 func (writer *recylceWriter) Write(buf []byte) (int, error) { 72 n, err := writer.writer.Write(buf) 73 bufPool.Put(buf) 74 return n, err 75 }