Repository navigation
Expand file tree
/
Copy pathencoder_json.go
More file actions
86 lines (78 loc) · 1.87 KB
/
Copy pathencoder_json.go
File metadata and controls
86 lines (78 loc) · 1.87 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package logger
// JSONEncoder emits one JSON object per line (ndjson) with OTEL-aligned keys.
// Configurable key names keep it compatible with downstream log backends.
type JSONEncoder struct {
TimeKey string
LevelKey string
MsgKey string
// NumericLevel emits the OTEL SeverityNumber instead of the band name.
NumericLevel bool
}
// NewJSONEncoder returns a JSONEncoder with conventional keys.
func NewJSONEncoder() JSONEncoder {
return JSONEncoder{TimeKey: "time", LevelKey: "level", MsgKey: "msg"}
}
// Name implements Encoder.
func (JSONEncoder) Name() string { return "json" }
// Encode implements Encoder.
func (e JSONEncoder) Encode(buf *buffer, r *Record) {
tk, lk, mk := e.TimeKey, e.LevelKey, e.MsgKey
if tk == "" {
tk = "time"
}
if lk == "" {
lk = "level"
}
if mk == "" {
mk = "msg"
}
buf.writeByte('{')
first := true
if !r.Time.IsZero() { // zero time → omit key (slog semantics)
buf.writeJSONString(tk)
buf.writeByte(':')
buf.writeByte('"')
buf.writeTimeRFC3339(r.Time)
buf.writeByte('"')
first = false
}
if !first {
buf.writeByte(',')
}
buf.writeJSONString(lk)
buf.writeByte(':')
if e.NumericLevel {
buf.writeInt(int64(r.Level))
} else {
buf.writeJSONString(r.Level.lower())
}
buf.writeByte(',')
buf.writeJSONString(mk)
buf.writeByte(':')
buf.writeJSONString(r.Message)
if r.EventName != "" {
buf.writeByte(',')
buf.writeJSONString("event")
buf.writeByte(':')
buf.writeJSONString(r.EventName)
}
if src, ok := r.source(); ok {
buf.writeByte(',')
buf.writeJSONString("caller")
buf.writeByte(':')
buf.writeByte('"')
buf.writeString(src.File)
buf.writeByte(':')
buf.writeInt(int64(src.Line))
buf.writeByte('"')
}
for i := range r.Fields {
f := &r.Fields[i]
buf.writeByte(',')
buf.writeJSONString(f.Key)
buf.writeByte(':')
appendFieldValue(buf, *f, true)
}
buf.writeByte('}')
buf.writeByte('\n')
}