-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllogger.go
386 lines (329 loc) · 10 KB
/
llogger.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// Package llogger simplifies printing messages to CloudWatch logs from AWS Lambda.
package llogger
import (
"context"
"encoding/json"
"fmt"
"runtime"
"time"
)
// var (
// w = time.Duration(0)
// c = time.Duration(0)
// )
// Client struct contains the state of the Client as well
// as channels for Warning and Critical time left until
// lambda deadline is reached.
type Client struct {
data Input
context context.Context
start time.Time
deadline time.Time
// w time.Duration
// c time.Duration
// The field names for loglevel, message, duration,
// time left and resource field names. Can be changed
// by setting llogger tfn-, llogger-llfn, llogger-mfn,
// llogger-dur, llogger-tl and llogger-res keys
// respectaviley in the inp when creating the client.
// If not set it will default to loglevel, message,
// duration, timeLeft and resource.
tfn string // time fieldname
llfn string // loglevel fieldname
mfn string // message fieldname
dfn string // duration fieldname
tlfn string // time left fieldname
rfn string // resource fieldname
// Prefix and suffixes
pre string // Prefix
suf string // Suffix
// The warning and critical log levels. Can be
// set by setting the llogger-wm and llogger-cm
// keys in inp when creating the client.
// If not set it will default to warning and
// error.
wm string // warning log level message
cm string // critical log level message
// The format used for the time field.
// Defaults to 2006-01-02 15:04:05.999999
// and can be overwritten with llogger-tf
// in Input.
tf string // Time format to use
// Warning chan<- time.Duration
// Critical chan<- time.Duration
}
// Input is used by the Print function to print information
// to stdout in JSON format. The JSON field will be called
// exactly as the name of the keys supplied.
type Input map[string]interface{}
type output map[string]interface{}
type resource struct {
Function string `json:"function"`
File string `json:"file"`
Row int `json:"row"`
}
// Print takes inp and prints it as a JSON to stdout.
// All fields left empty will be omitted in the JSON output.
// If ctx was set to nil in *Client Duration and TimeLeft will
// not be set.
func (l *Client) Print(inp Input) {
// Creates a basic output that merges data form l and inp.
out := l.createOutput(inp)
// Fetch and set the calling function filename and line.
// This call will never fail since skip is 1 and there
// is always a caller. So skip ok variable.
fptr, file, row, _ := runtime.Caller(1)
funcName := runtime.FuncForPC(fptr).Name()
out[l.rfn] = resource{
Function: funcName,
File: file,
Row: row,
}
raw, err := json.Marshal(out)
switch {
// If JSON Marshal fails print a error message about failing JSON Marshal.
// Don't print the original error message since it probably contains not so
// good data that possibly could break other things.
case err != nil:
l.Print(Input{l.llfn: l.cm, l.mfn: "Couldn't JSON marshal the error message"})
default:
fmt.Printf("%s%s%s\n", l.pre, raw, l.suf)
}
}
// createOutput will return output that contains the
// merged data from l.data and inp. If l.context is
// set duration and time_left will also be set based
// on data from the lambda context.
// Returns output.
func (l *Client) createOutput(inp Input) output {
out := output{}
switch l.tf {
case "Unix":
out[l.tfn] = time.Now().Unix()
case "UnixNano":
out[l.tfn] = time.Now().UnixNano()
default:
out[l.tfn] = time.Now().Format(l.tf)
}
// Merge Input from l and Input.
for k, v := range l.data {
out[k] = v
}
for k, v := range inp {
out[k] = v
}
// Set duration and time_left if context is set.
if l.context != nil {
out[l.dfn] = time.Now().Sub(l.start).Seconds()
out[l.tlfn] = l.deadline.Sub(time.Now()).Seconds()
}
return out
}
// Create takes context ctx and Input inp and creates a llogger client. The llogger
// client can then be used to print JSON messages to CloudWatch logs.
// ctx should be a valid context created by AWS Lambda. If set to nil all additional
// functionality that requires context will be disabled such as getting lambda duration,
// time left. The channels for time left warnings will also never trigger.
// All data specified in inp will be added to each message sent by the client.
// You can also specify the "log level" and "message" field name by adding the special
// variables llfn for "log level field name" anf mfn "message field name" to inp.
// If context as set and as a valid AWS Lambda context there will be events on the
// l.Warning and l.Critical channels when the lambda detects that only 25% and 10%
// respectively of runtime is left before it will self terminate.
// Returns *Client.
func Create(ctx context.Context, inp Input) *Client {
l := &Client{
data: inp,
start: time.Now().UTC(),
context: ctx,
}
// Set the loglevel and message field names.
l.setFieldNames()
// Set the warning and critical error messages..
l.setErrorMessages()
// Set the format to use for time.
l.setTimeFormat()
// Set the context.
l.UpdateContext(ctx)
return l
}
// UpdateContext updates the context of the Client. This is useful
// when you have a persistent llogger in your code but want to update
// the context on each iteration.
func (l *Client) UpdateContext(ctx context.Context) {
// If context is nil there is no need to set the context.
if ctx == nil {
return
}
// Set context.
l.context = ctx
// If we can't get Deadline from context set context to nil and
// print an error message.
d, ok := l.context.Deadline()
switch {
case !ok:
l.context = nil
l.Print(Input{l.llfn: l.cm, l.mfn: "Couldn't get Deadline from context"})
return
default:
l.deadline = d.UTC()
}
// Set duration, warning and critical levels.
// And create the channels for sending messages
// back to the calling function.
// dur := l.deadline.Sub(l.start)
// w = 0
// c = 0
// w = dur * 3 / 4
// c = dur * 9 / 19
// fmt.Println("w", l.w)
// fmt.Println("c", l.c)
// l.Warning = make(chan<- time.Duration)
// l.Critical = make(chan<- time.Duration)
// fmt.Println(runtime.NumGoroutine())
// go l.warning(w)
// go l.critical(c)
}
// func (l *Client) Close() {
// l.
// }
// func (l *Client) warning(w time.Duration) {
// select {
// default:
// time.Sleep(time.Duration(100*time.Millisecond))
// }
// time.Sleep(w)
// l.Print(Input{l.llfn: l.wm, l.mfn: "Only 25% of execution time left"})
// l.Warning <- l.deadline.Sub(time.Now())
// }
// func (l *Client) critical(c time.Duration) {
// time.Sleep(c)
// l.Print(Input{l.llfn: l.cm, l.mfn: "Only 10% of execution time left"})
// l.Critical <- l.deadline.Sub(time.Now())
// }
// setFieldNames will set the default key names for the log level and message
// field. If not specified by env variables it will default to "loglevel"
// and "message".
func (l *Client) setFieldNames() {
// Try and get Time Field Name from l.data as a string.
if tfn, ok := l.data["llogger-tfn"]; ok {
if str, ok := tfn.(string); ok {
l.tfn = str
}
delete(l.data, "llogger-tfn")
}
// Try and get Log Level Field Name from l.data as a string.
if llfn, ok := l.data["llogger-llfn"]; ok {
if str, ok := llfn.(string); ok {
l.llfn = str
}
delete(l.data, "llogger-llfn")
}
// Try and get Message Field Name from l.data as a string.
if mfn, ok := l.data["llogger-mfn"]; ok {
if str, ok := mfn.(string); ok {
l.mfn = str
}
delete(l.data, "llogger-mfn")
}
// Try and get Duration Field Name from l.data as a string.
if dfn, ok := l.data["llogger-dfn"]; ok {
if str, ok := dfn.(string); ok {
l.dfn = str
}
delete(l.data, "llogger-dfn")
}
// Try and get Time Left Field Name from l.data as a string.
if tlfn, ok := l.data["llogger-tlfn"]; ok {
if str, ok := tlfn.(string); ok {
l.tlfn = str
}
delete(l.data, "llogger-tlfn")
}
// Try and get Resource Field Name from l.data as a string.
if rfn, ok := l.data["llogger-rfn"]; ok {
if str, ok := rfn.(string); ok {
l.rfn = str
}
delete(l.data, "llogger-rfn")
}
// Add prefix to output if supplied.
if pre, ok := l.data["llogger-prefix"]; ok {
if str, ok := pre.(string); ok {
l.pre = str
}
delete(l.data, "llogger-prefix")
}
// Add suffix to output if supplied.
if suf, ok := l.data["llogger-suffix"]; ok {
if str, ok := suf.(string); ok {
l.suf = str
}
delete(l.data, "llogger-suffix")
}
// Check that Log Level and Message is not empty. If they are empty
// default to field names "time", loglevel", "message", "duration",
// "timeLeft" and "resource".
if l.tfn == "" {
l.tfn = "time"
}
if l.llfn == "" {
l.llfn = "loglevel"
}
if l.mfn == "" {
l.mfn = "message"
}
if l.dfn == "" {
l.dfn = "duration"
}
if l.tlfn == "" {
l.tlfn = "timeLeft"
}
if l.rfn == "" {
l.rfn = "resource"
}
}
// setErrorMessages will set the default log level warning and error messages
// If not specified by env variables it will default to "warning"
// and "error".
func (l *Client) setErrorMessages() {
// Try and get Warning Message from l.data as a string.
if wm, ok := l.data["llogger-wm"]; ok {
if str, ok := wm.(string); ok {
l.wm = str
}
delete(l.data, "llogger-wm")
}
// Try and get Critical Message from l.data as a string.
if cm, ok := l.data["llogger-cm"]; ok {
if str, ok := cm.(string); ok {
l.cm = str
}
delete(l.data, "llogger-cm")
}
// Check that Warning and Critical Messages are not empty. If they are empty
// default to field names "warning" and "error".
if l.wm == "" {
l.wm = "warning"
}
if l.cm == "" {
l.cm = "error"
}
}
// setTimeFormat will set the format to use for showing "time". Will default
// to "2006-01-02 15:04:05.999999". All golang time formats can be used.
// For list and manual parse see https://golang.org/src/time/format.go
func (l *Client) setTimeFormat() {
// Try and get Warning Message from l.data as a string.
if tf, ok := l.data["llogger-tf"]; ok {
if str, ok := tf.(string); ok {
l.tf = str
}
delete(l.data, "llogger-tf")
}
// Check that format was set. If empty set to default
// 2006-01-02 15:04:05.999999.
if l.tf == "" {
l.tf = "2006-01-02 15:04:05.999999"
}
}