github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/countlog/output/json/json.go (about) 1 package json 2 3 import ( 4 "github.com/v2pro/plz/countlog/output" 5 "github.com/v2pro/plz/countlog/spi" 6 "github.com/v2pro/plz/msgfmt/jsonfmt" 7 "github.com/v2pro/plz/reflect2" 8 ) 9 10 type JsonFormat struct { 11 } 12 13 func (format *JsonFormat) FormatterOf(site *spi.LogSite) output.Formatter { 14 formatter := &jsonFormatter{ 15 prefix: `{"event":"` + site.Event + `"`, 16 suffix: `,location:"` + site.Location() + `"}` + "\n", 17 timestampEncoder: jsonfmt.EncoderOf(reflect2.TypeOf(int64(0))), 18 } 19 for i := 0; i < len(site.Sample); i += 2 { 20 prefix := `"` + site.Sample[i].(string) + `":` 21 formatter.props = append(formatter.props, jsonFormatterProp{ 22 prefix: prefix, 23 idx: i + 1, 24 encoder: jsonfmt.EncoderOf(reflect2.TypeOf(site.Sample[i+1])), 25 }) 26 } 27 return formatter 28 } 29 30 type jsonFormatter struct { 31 prefix string 32 suffix string 33 props []jsonFormatterProp 34 timestampEncoder jsonfmt.Encoder 35 } 36 37 type jsonFormatterProp struct { 38 prefix string 39 idx int 40 encoder jsonfmt.Encoder 41 } 42 43 func (formatter *jsonFormatter) Format(space []byte, event *spi.Event) []byte { 44 space = append(space, formatter.prefix...) 45 for _, prop := range formatter.props { 46 space = append(space, ',') 47 space = append(space, prop.prefix...) 48 space = prop.encoder.Encode(nil, space, reflect2.PtrOf(event.Properties[prop.idx])) 49 } 50 space = append(space, ",timestamp:"...) 51 space = formatter.timestampEncoder.Encode(nil, space, reflect2.PtrOf(event.Timestamp.UnixNano())) 52 space = append(space, formatter.suffix...) 53 return space 54 }