@@ -7,93 +7,17 @@ package logx
77
88import (
99 "bytes"
10- "encoding/json"
11- "fmt"
12- "strings"
13- "time"
10+ "io"
1411
1512 "go.osspkg.com/ioutils/pool"
1613)
1714
18- type Formatter interface {
19- Encode (m * Message ) ([]byte , error )
20- }
21-
2215var newLine = []byte ("\n " )
2316
24- // //////////////////////////////////////////////////////////////////////////////
25-
26- type FormatJSON struct {}
27-
28- func NewFormatJSON () * FormatJSON {
29- return & FormatJSON {}
30- }
31-
32- func (* FormatJSON ) Encode (m * Message ) ([]byte , error ) {
33- m .CtxToMap ()
34- b , err := json .Marshal (m )
35- if err != nil {
36- return nil , err
37- }
38- return append (b , '\n' ), nil
39- }
40-
41- // //////////////////////////////////////////////////////////////////////////////
42-
43- var poolBuff = pool.New [* bytes.Buffer ](func () * bytes.Buffer {
17+ var poolBuffer = pool.New [* bytes.Buffer ](func () * bytes.Buffer {
4418 return bytes .NewBuffer (make ([]byte , 0 , 1024 ))
4519})
4620
47- type FormatString struct {
48- delim string
49- }
50-
51- func NewFormatString () * FormatString {
52- return & FormatString {delim : "\t " }
53- }
54-
55- func (v * FormatString ) SetDelimiter (d string ) {
56- v .delim = d
57- }
58-
59- func (v * FormatString ) Encode (m * Message ) ([]byte , error ) {
60- buff := poolBuff .Get ()
61- defer func () {
62- poolBuff .Put (buff )
63- }()
64-
65- fmt .Fprintf (buff , "time=%s%slvl=%s%smsg=%#v" ,
66- m .Time .Format (time .RFC3339 ), v .delim , m .Level , v .delim , m .Message )
67-
68- if count := len (m .Ctx ); count > 0 {
69- if count % 2 != 0 {
70- m .Ctx = append (m .Ctx , nil )
71- count ++
72- }
73- for i := 0 ; i < count ; i = i + 2 {
74- fmt .Fprintf (buff , "%s%s=\" %s\" " , v .delim , typing (m .Ctx [i ]), typing (m .Ctx [i + 1 ]))
75- }
76- }
77- buff .Write (newLine )
78-
79- return append (make ([]byte , 0 , buff .Len ()), buff .Bytes ()... ), nil
80- }
81-
82- func typing (v interface {}) (s string ) {
83- if v == nil {
84- s = "null"
85- return
86- }
87- switch vv := v .(type ) {
88- case error :
89- s = vv .Error ()
90- case fmt.GoStringer :
91- s = vv .GoString ()
92- case fmt.Stringer :
93- s = vv .String ()
94- default :
95- s = fmt .Sprintf ("%#v" , v )
96- }
97- s = strings .Trim (s , "\" " )
98- return
21+ type Formatter interface {
22+ Encode (w io.Writer , m * Message ) error
9923}
0 commit comments