-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
244 lines (217 loc) · 6.96 KB
/
writer.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package atzerolog // import "go.atatus.com/agent/module/atzerolog"
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"io"
"strconv"
"time"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/pkgerrors"
atatus "go.atatus.com/agent"
"go.atatus.com/agent/stacktrace"
)
const (
// DefaultFatalFlushTimeout is the default value for Writer.FatalFlushTimeout.
DefaultFatalFlushTimeout = 5 * time.Second
// StackSourceLineName is the key for the line number of a stack frame.
StackSourceLineName = "line"
// StackSourceFunctionName is the key for the function name of a stack frame.
StackSourceFunctionName = "func"
)
func init() {
stacktrace.RegisterLibraryPackage("github.com/rs/zerolog")
}
// Writer is an implementation of zerolog.LevelWriter, reporting log records as
// errors to the APM Server. If TraceContext is used to add trace IDs to the log
// records, the errors reported will be associated with them.
//
// Because we only have access to the serialised form of the log record, we must
// rely on enough information being encoded into the events. For error stack traces,
// you must use zerolog's Stack() method, and set zerolog.ErrorStackMarshaler
// either to github.com/rs/zerolog/pkgerrors.MarshalStack, or to the function
// atzerolog.MarshalErrorStack in this package. The pkgerrors.MarshalStack
// implementation omits some information, whereas atzerolog is designed to
// convey the complete file location and fully qualified function name.
type Writer struct {
// Tracer is the atatus.Tracer to use for reporting errors.
// If Tracer is nil, then atatus.DefaultTracer will be used.
Tracer *atatus.Tracer
// FatalFlushTimeout is the amount of time to wait while
// flushing a fatal log message to the APM Server before
// the process is exited. If this is 0, then
// DefaultFatalFlushTimeout will be used. If the timeout
// is a negative value, then no flushing will be performed.
FatalFlushTimeout time.Duration
// MinLevel holds the minimum level of logs to send to
// Atatus as errors.
//
// MinLevel must be greater than or equal to zerolog.ErrorLevel.
// If it is less than this, zerolog.ErrorLevel will be used as
// the minimum instead.
MinLevel zerolog.Level
}
func (w *Writer) tracer() *atatus.Tracer {
tracer := w.Tracer
if tracer == nil {
tracer = atatus.DefaultTracer
}
return tracer
}
func (w *Writer) minLevel() zerolog.Level {
minLevel := w.MinLevel
if minLevel < zerolog.ErrorLevel {
minLevel = zerolog.ErrorLevel
}
return minLevel
}
// Write is a no-op.
func (*Writer) Write(p []byte) (int, error) {
return len(p), nil
}
// WriteLevel decodes the JSON-encoded log record in p, and reports it as an error using w.Tracer.
func (w *Writer) WriteLevel(level zerolog.Level, p []byte) (int, error) {
if level < w.minLevel() || level >= zerolog.NoLevel {
return len(p), nil
}
tracer := w.tracer()
if !tracer.Recording() {
return len(p), nil
}
var logRecord logRecord
if err := logRecord.decode(bytes.NewReader(p)); err != nil {
return 0, err
}
errlog := tracer.NewErrorLog(atatus.ErrorLogRecord{
Level: level.String(),
Message: logRecord.message,
Error: logRecord.err,
})
if !logRecord.timestamp.IsZero() {
errlog.Timestamp = logRecord.timestamp
}
errlog.Handled = true
errlog.SetStacktrace(1)
errlog.TraceID = logRecord.traceID
errlog.TransactionID = logRecord.transactionID
if logRecord.spanID.Validate() == nil {
errlog.ParentID = logRecord.spanID
} else {
errlog.ParentID = logRecord.transactionID
}
errlog.Send()
if level == zerolog.FatalLevel {
// Zap will exit the process following a fatal log message, so we flush the tracer.
flushTimeout := w.FatalFlushTimeout
if flushTimeout == 0 {
flushTimeout = DefaultFatalFlushTimeout
}
if flushTimeout >= 0 {
ctx, cancel := context.WithTimeout(context.Background(), flushTimeout)
defer cancel()
tracer.Flush(ctx.Done())
}
}
return len(p), nil
}
type logRecord struct {
message string
timestamp time.Time
err error
traceID atatus.TraceID
transactionID, spanID atatus.SpanID
}
func (l *logRecord) decode(r io.Reader) (result error) {
m := make(map[string]interface{})
d := json.NewDecoder(r)
d.UseNumber()
if err := d.Decode(&m); err != nil {
return err
}
l.message, _ = m[zerolog.MessageFieldName].(string)
if strval, ok := m[zerolog.TimestampFieldName].(string); ok {
if t, err := time.Parse(zerolog.TimeFieldFormat, strval); err == nil {
l.timestamp = t.UTC()
}
}
if errmsg, ok := m[zerolog.ErrorFieldName].(string); ok {
err := &jsonError{message: errmsg}
if stack, ok := m[zerolog.ErrorStackFieldName].([]interface{}); ok {
frames := make([]stacktrace.Frame, 0, len(stack))
for i := range stack {
in, ok := stack[i].(map[string]interface{})
if !ok {
continue
}
var frame stacktrace.Frame
frame.File, _ = in[pkgerrors.StackSourceFileName].(string)
frame.Function, _ = in[StackSourceFunctionName].(string)
if strval, ok := in[StackSourceLineName].(string); ok {
if line, err := strconv.Atoi(strval); err == nil {
frame.Line = line
}
}
frames = append(frames, frame)
}
err.stack = frames
}
l.err = err
}
if strval, ok := m[SpanIDFieldName].(string); ok {
if err := decodeHex(l.spanID[:], strval); err != nil {
return errors.Wrap(err, "invalid span.id")
}
}
if strval, ok := m[TraceIDFieldName].(string); ok {
if err := decodeHex(l.traceID[:], strval); err != nil {
return errors.Wrap(err, "invalid trace.id")
}
}
if strval, ok := m[TransactionIDFieldName].(string); ok {
if err := decodeHex(l.transactionID[:], strval); err != nil {
return errors.Wrap(err, "invalid transaction.id")
}
}
return nil
}
func decodeHex(out []byte, in string) error {
if n := hex.EncodedLen(len(out)); n != len(in) {
return errors.Errorf(
"invalid value length (expected %d bytes, got %d)",
n, len(in),
)
}
_, err := hex.Decode(out, []byte(in))
return err
}
type jsonError struct {
message string
stack []stacktrace.Frame
}
func (e *jsonError) Type() string {
return "error"
}
func (e *jsonError) Error() string {
return e.message
}
func (e *jsonError) StackTrace() []stacktrace.Frame {
return e.stack
}