-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformatter_logfmt.go
65 lines (51 loc) · 1.41 KB
/
formatter_logfmt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright The ActForGood Authors.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://github.com/actforgood/xlog/blob/main/LICENSE.
package xlog
import (
"bytes"
"io"
"sync"
"github.com/go-logfmt/logfmt"
)
type logfmtEncoder struct {
*logfmt.Encoder
buf bytes.Buffer
}
// Reset resets the encoder and its buffer.
func (enc *logfmtEncoder) Reset() {
enc.Encoder.Reset()
enc.buf.Reset()
}
// Encode encodes given key values in logfmt format.
func (enc *logfmtEncoder) Encode(keyValues ...any) error {
if err := enc.EncodeKeyvals(keyValues...); err != nil {
return err
}
return enc.EndRecord()
}
var logfmtEncoderPool = sync.Pool{
New: func() any {
enc := new(logfmtEncoder)
enc.Encoder = logfmt.NewEncoder(&enc.buf)
return enc
},
}
// LogfmtFormatter serializes key-values in logfmt format and writes the
// resulted bytes to the writer.
// It returns error if a serialization/writing problem is encountered.
// More about logfmt can be found here: https://brandur.org/logfmt .
var LogfmtFormatter Formatter = func(w io.Writer, keyValues []any) error {
keyValues = AppendNoValue(keyValues)
enc := logfmtEncoderPool.Get().(*logfmtEncoder)
enc.Reset()
defer logfmtEncoderPool.Put(enc)
if err := enc.Encode(keyValues...); err != nil {
return err
}
if _, err := w.Write(enc.buf.Bytes()); err != nil {
return err
}
return nil
}