-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
303 lines (269 loc) · 8.46 KB
/
request.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package logjam
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/golang/snappy"
)
// Request encapsulates information about the current logjam request.
type Request struct {
agent *Agent // logjam agent
action string // The action name for this request.
uuid string // Request id as sent to logjam (version 4 UUID).
id string // Request id as sent to called applications (app-env-uuid).
callerID string // Request id of the caller (if any).
callerAction string // Action name of the caller (if any).
traceID string // Trace id for this request.
startTime time.Time // Start time of this request.
endTime time.Time // Completion time of this request.
durations map[string]time.Duration // Time metrics.
counts map[string]int64 // Counters.
logLines []interface{} // Log lines.
logLinesBytesCount int // Byte size of logged lines.
severity LogLevel // Max log severity over all log lines.
fields map[string]interface{} // Additional kye vale pairs for JSON payload sent to logjam.
info map[string]interface{} // Information about the associated HTTP request.
ip string // IP of the HTTP request originator.
exceptions map[string]bool // List of exception tags to send to logjam.
mutex sync.Mutex // Mutex for protecting mutators
}
// NewRequest creates a new logjam request for a given action name.
func (a *Agent) NewRequest(action string) *Request {
r := Request{
agent: a,
action: action,
durations: map[string]time.Duration{},
counts: map[string]int64{},
fields: map[string]interface{}{},
logLines: []interface{}{},
exceptions: map[string]bool{},
severity: INFO,
}
r.startTime = time.Now()
r.uuid = generateUUID()
r.traceID = r.uuid
r.id = a.AppName + "-" + a.EnvName + "-" + r.uuid
return &r
}
type contextKey int
const (
requestKey contextKey = 0
)
// NewContext creates a new context with the request added.
func (r *Request) NewContext(c context.Context) context.Context {
return context.WithValue(c, requestKey, r)
}
// AugmentRequest extends a given http request with a logjam request stored in its context.
func (r *Request) AugmentRequest(incoming *http.Request) *http.Request {
return incoming.WithContext(r.NewContext(incoming.Context()))
}
// ChangeAction changes the action name and updates the corresponding header on the given
// http request writer.
func (r *Request) ChangeAction(w http.ResponseWriter, action string) {
r.action = action
w.Header().Set("X-Logjam-Action", action)
}
// GetRequest retrieves a logjam request from an Context. Returns nil if no
// request is stored in the context.
func GetRequest(ctx context.Context) *Request {
v, ok := ctx.Value(requestKey).(*Request)
if ok {
return v
}
return nil
}
// Log adds a log line to be sent to logjam to the request.
func (r *Request) Log(severity LogLevel, line string) {
r.mutex.Lock()
defer r.mutex.Unlock()
if severity > FATAL {
severity = FATAL
} else if severity < DEBUG {
severity = DEBUG
}
if r.severity < severity {
r.severity = severity
}
if r.agent.LogLevel > severity {
return
}
if r.logLinesBytesCount > r.agent.MaxBytesAllLines {
return
}
lineLen := len(line)
r.logLinesBytesCount += lineLen
if r.logLinesBytesCount < r.agent.MaxBytesAllLines {
r.logLines = append(r.logLines, formatLine(severity, time.Now(), line, r.agent.MaxLineLength))
} else {
r.logLines = append(r.logLines, formatLine(severity, time.Now(), linesTruncated, r.agent.MaxLineLength))
}
}
// SetField sets an additional key value pair on the request.
func (r *Request) SetField(key string, value interface{}) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.fields[key] = value
}
// GetField retrieves sets an additional key value pair on the request.
func (r *Request) GetField(key string) interface{} {
r.mutex.Lock()
defer r.mutex.Unlock()
return r.fields[key]
}
// AddException adds an exception tag to be sent to logjam.
func (r *Request) AddException(name string) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.exceptions[name] = true
}
// AddCount increments a counter metric associated with this request.
func (r *Request) AddCount(key string, value int64) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.counts[key] += value
}
// Count behaves like AddCount with a value of 1
func (r *Request) Count(key string) {
r.AddCount(key, 1)
}
// AddDuration increases increments a timer metric associated with this request.
func (r *Request) AddDuration(key string, value time.Duration) {
r.mutex.Lock()
defer r.mutex.Unlock()
if _, set := r.durations[key]; set {
r.durations[key] += value
} else {
r.durations[key] = value
}
}
// MeasureDuration is a helper function that records the duration of execution of the
// passed function in cases where it is cumbersome to just use AddDuration instead.
func (r *Request) MeasureDuration(key string, f func()) {
beginning := time.Now()
defer func() { r.AddDuration(key, time.Since(beginning)) }()
f()
}
// Finish adds the response code to the requests and sends it to logjam.
func (r *Request) Finish(code int) {
r.endTime = time.Now()
payload := r.logjamPayload(code)
buf, err := json.Marshal(&payload)
if err != nil {
r.agent.Logger.Println(err)
return
}
data := snappy.Encode(nil, buf)
r.agent.sendMessage(data)
}
func (r *Request) durationCorrectionFactor(totalTime float64) float64 {
s := float64(0)
for _, d := range r.durations {
s += float64(d / time.Millisecond)
}
if s > totalTime {
return (totalTime - 0.1) / s
}
return 1.0
}
func (r *Request) logjamPayload(code int) map[string]interface{} {
totalTime := r.totalTime()
msg := map[string]interface{}{
"action": r.action,
"code": code,
"process_id": os.Getpid(),
"request_id": r.uuid,
"trace_id": r.traceID,
"severity": r.severity,
"started_at": r.startTime.Format(timeFormat),
"started_ms": r.startTime.UnixNano() / 1000000,
"total_time": totalTime,
}
if len(r.logLines) > 0 {
msg["lines"] = r.logLines
}
if len(r.info) > 0 {
msg["request_info"] = r.info
}
if r.ip != "" {
msg["ip"] = r.ip
}
if r.callerID != "" {
msg["caller_id"] = r.callerID
}
if r.callerAction != "" {
msg["caller_action"] = r.callerAction
}
if len(r.exceptions) > 0 {
exceptions := []string{}
for name := range r.exceptions {
exceptions = append(exceptions, name)
}
msg["exceptions"] = exceptions
}
for key, val := range requestEnv {
msg[key] = val
}
c := r.durationCorrectionFactor(totalTime)
for key, duration := range r.durations {
msg[key] = c * float64(duration/time.Millisecond)
}
for key, count := range r.counts {
msg[key] = count
}
for key, val := range r.fields {
msg[key] = val
}
return msg
}
func (r *Request) totalTime() float64 {
return float64(r.endTime.Sub(r.startTime)) / float64(time.Millisecond)
}
var requestEnv = make(map[string]string, 0)
func init() {
setRequestEnv()
}
func setRequestEnv() {
m := map[string]string{
"host": "HOSTNAME",
"cluster": "CLUSTER",
"datacenter": "DATACENTER",
"namespace": "NAMESPACE",
}
for key, envVarName := range m {
if v := os.Getenv(envVarName); v != "" {
requestEnv[key] = v
}
}
}
// generateUUID provides a Logjam compatible UUID, which means it doesn't adhere to the
// standard by having the dashes removed.
func generateUUID() string {
uuid := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, uuid); err != nil {
log.Fatalln(err)
}
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
var hexbuf [32]byte
hex.Encode(hexbuf[:], uuid[:])
return string(hexbuf[:])
}
const timeFormat = "2006-01-02T15:04:05.000000"
const lineTruncated = " ... [LINE TRUNCATED]"
const linesTruncated = "... [LINES DROPPED]"
func formatLine(severity LogLevel, timeStamp time.Time, message string, maxLineLength int) []interface{} {
if len(message) > maxLineLength {
message = message[0:maxLineLength-len(lineTruncated)] + lineTruncated
}
return []interface{}{int(severity), formatTime(timeStamp), message}
}
func formatTime(timeStamp time.Time) string {
return timeStamp.Format(timeFormat)
}