Debian Codegraph @

event/adapter/logfmt/logfmt.go

raw symbols SCIP
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package logfmt
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11 "io"
12 "strconv"
13 "time"
14 "unicode/utf8"
15
16 "golang.org/x/exp/event"
17 )
18
19 // TODO: some actual research into what this arbritray optimization number should be
20 const bufCap = 50
21
22 const TimeFormat = "2006/01/02 15:04:05"
23
24 type Printer struct {
25 QuoteValues bool
26 SuppressNamespace bool
27 buf [bufCap]byte
28 needSep bool
29 w bytes.Buffer
30 }
31
32 type Handler struct {
33 to io.Writer
34 Printer
35 }
36
37 // NewHandler returns a handler that prints the events to the supplied writer.
38 // Each event is printed in logfmt format on a single line.
39 func NewHandler(to io.Writer) *Handler {
40 return &Handler{to: to}
41 }
42
43 func (h *Handler) Event(ctx context.Context, ev *event.Event) context.Context {
44 h.Printer.Event(h.to, ev)
45 return ctx
46 }
47
48 func (p *Printer) Event(w io.Writer, ev *event.Event) {
49 p.needSep = false
50 if !ev.At.IsZero() {
51 p.separator(w)
52 io.WriteString(w, `time="`)
53 p.time(w, ev.At)
54 io.WriteString(w, `"`)
55 }
56
57 if !p.SuppressNamespace && ev.Source.Space != "" {
58 p.Label(w, event.String("in", ev.Source.Space))
59 }
60 if ev.Source.Owner != "" {
61 p.Label(w, event.String("owner", ev.Source.Owner))
62 }
63 if ev.Source.Name != "" {
64 p.Label(w, event.String("name", ev.Source.Name))
65 }
66
67 if ev.Parent != 0 {
68 p.separator(w)
69 io.WriteString(w, `parent=`)
70 w.Write(strconv.AppendUint(p.buf[:0], ev.Parent, 10))
71 }
72 for _, l := range ev.Labels {
73 if l.Name == "" {
74 continue
75 }
76 p.Label(w, l)
77 }
78
79 if ev.ID != 0 && ev.Kind == event.StartKind {
80 p.separator(w)
81 io.WriteString(w, `trace=`)
82 w.Write(strconv.AppendUint(p.buf[:0], ev.ID, 10))
83 }
84
85 if ev.Kind == event.EndKind {
86 p.separator(w)
87 io.WriteString(w, `end`)
88 }
89
90 io.WriteString(w, "\n")
91 }
92
93 func (p *Printer) separator(w io.Writer) {
94 if p.needSep {
95 io.WriteString(w, " ")
96 }
97 p.needSep = true
98 }
99
100 func (p *Printer) Label(w io.Writer, l event.Label) {
101 if l.Name == "" {
102 return
103 }
104 p.separator(w)
105 p.Ident(w, l.Name)
106 if l.HasValue() {
107 io.WriteString(w, "=")
108 switch {
109 case l.IsString():
110 p.string(w, l.String())
111 case l.IsBytes():
112 p.bytes(w, l.Bytes())
113 case l.IsInt64():
114 w.Write(strconv.AppendInt(p.buf[:0], l.Int64(), 10))
115 case l.IsUint64():
116 w.Write(strconv.AppendUint(p.buf[:0], l.Uint64(), 10))
117 case l.IsFloat64():
118 w.Write(strconv.AppendFloat(p.buf[:0], l.Float64(), 'g', -1, 64))
119 case l.IsBool():
120 if l.Bool() {
121 io.WriteString(w, "true")
122 } else {
123 io.WriteString(w, "false")
124 }
125 default:
126 v := l.Interface()
127 switch v := v.(type) {
128 case string:
129 p.string(w, v)
130 case fmt.Stringer:
131 p.string(w, v.String())
132 default:
133 if p.w.Cap() == 0 {
134 // we rely on the inliner to cause this to not allocate
135 p.w = *bytes.NewBuffer(p.buf[:0])
136 }
137 fmt.Fprint(&p.w, v)
138 b := p.w.Bytes()
139 p.w.Reset()
140 p.bytes(w, b)
141 }
142 }
143 }
144 }
145
146 func (p *Printer) Ident(w io.Writer, s string) {
147 if !stringNeedQuote(s) {
148 io.WriteString(w, s)
149 return
150 }
151 p.quoteString(w, s)
152 }
153
154 func (p *Printer) string(w io.Writer, s string) {
155 if p.QuoteValues || stringNeedQuote(s) {
156 p.quoteString(w, s)
157 } else {
158 io.WriteString(w, s)
159 }
160 }
161
162 func (p *Printer) quoteString(w io.Writer, s string) {
163 io.WriteString(w, `"`)
164 written := 0
165 for offset, r := range s {
166 q := quoteRune(r)
167 if len(q) == 0 {
168 continue
169 }
170 // write out any prefix
171 io.WriteString(w, s[written:offset])
172 written = offset + utf8.RuneLen(r)
173 // and write out the quoted rune
174 io.WriteString(w, q)
175 }
176 io.WriteString(w, s[written:])
177 io.WriteString(w, `"`)
178 }
179
180 func (p *Printer) bytes(w io.Writer, buf []byte) {
181 if p.QuoteValues || stringNeedQuote(string(buf)) {
182 p.quoteBytes(w, buf)
183 } else {
184 w.Write(buf)
185 }
186 }
187
188 // Bytes writes a byte array in string form to the printer.
189 func (p *Printer) quoteBytes(w io.Writer, buf []byte) {
190 io.WriteString(w, `"`)
191 written := 0
192 for offset := 0; offset < len(buf); {
193 r, size := utf8.DecodeRune(buf[offset:])
194 offset += size
195 q := quoteRune(r)
196 if len(q) == 0 {
197 continue
198 }
199 // write out any prefix
200 w.Write(buf[written : offset-size])
201 written = offset
202 // and write out the quoted rune
203 io.WriteString(w, q)
204 }
205 w.Write(buf[written:])
206 io.WriteString(w, `"`)
207 }
208
209 // time writes a timestamp in the same format as
210 func (p *Printer) time(w io.Writer, t time.Time) {
211 year, month, day := t.Date()
212 hour, minute, second := t.Clock()
213 p.padInt(w, int64(year), 4)
214 io.WriteString(w, `/`)
215 p.padInt(w, int64(month), 2)
216 io.WriteString(w, `/`)
217 p.padInt(w, int64(day), 2)
218 io.WriteString(w, ` `)
219 p.padInt(w, int64(hour), 2)
220 io.WriteString(w, `:`)
221 p.padInt(w, int64(minute), 2)
222 io.WriteString(w, `:`)
223 p.padInt(w, int64(second), 2)
224 }
225
226 func (p *Printer) padInt(w io.Writer, v int64, width int) {
227 b := strconv.AppendInt(p.buf[:0], int64(v), 10)
228 if len(b) < width {
229 io.WriteString(w, "0000"[:width-len(b)])
230 }
231 w.Write(b)
232 }
233
234 func stringNeedQuote(s string) bool {
235 if len(s) == 0 {
236 return true
237 }
238 for i := 0; i < len(s); i++ {
239 c := s[i]
240 if c >= utf8.RuneSelf || c == ' ' || c == '"' || c == '\n' || c == '\\' {
241 return true
242 }
243 }
244 return false
245 }
246
247 func quoteRune(r rune) string {
248 switch r {
249 case '"':
250 return `\"`
251 case '\n':
252 return `\n`
253 case '\\':
254 return `\\`
255 default:
256 return ``
257 }
258 }