-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda-log-context.go
275 lines (245 loc) · 7.46 KB
/
lambda-log-context.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
// Copyright © 2018 Douglas Chimento <[email protected]>
//
// Licensed 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 lambdazap
import (
"context"
"os"
"github.com/aws/aws-lambda-go/lambdacontext"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// LambdaField type alias
type LambdaField int
// Enums for fields
const (
AwsRequestID LambdaField = iota
CognitoIdentityID
CognitoIdentityPoolID
InstallationID
AppTitle
AppVersionCode
AppPackageName
InvokeFunctionArn
FunctionName
FunctionVersion
LogGroupName
LogStreamName
MemoryLimitInMB
END
)
const staticStartIndex = 8
// DefaultNames of fields
var DefaultNames = []string{
AwsRequestID: "requestId",
FunctionName: "functionName",
FunctionVersion: "functionVersion",
LogGroupName: "logGroupName",
LogStreamName: "logStreamName",
InvokeFunctionArn: "arn",
CognitoIdentityID: "cognitoIdentityId",
CognitoIdentityPoolID: "cognitoIdentityPoolId",
InstallationID: "installationId",
AppTitle: "appTitle",
AppVersionCode: "appVersionCode",
AppPackageName: "appPackageName",
MemoryLimitInMB: "memoryLimitInMB",
}
// An Option configures a Logger.
type Option interface {
apply(*LambdaLogContext)
}
type optionFunc func(*LambdaLogContext)
func (f optionFunc) apply(lc *LambdaLogContext) {
f(lc)
}
// CustomNames for fields
func CustomNames(n map[LambdaField]string) Option {
return optionFunc(func(lc *LambdaLogContext) {
lc.customNames = n
})
}
// CustomValues override context values. if you return an error the default ContextValue will be used.
func CustomValues(c ContextValuer) Option {
return optionFunc(func(lc *LambdaLogContext) {
lc.customBuilder = c
})
}
// ProcessNonContextFields when calling ContextValues include or not include
// Values that are not part of the lambda context
func ProcessNonContextFields(b bool) Option {
return optionFunc(func(lc *LambdaLogContext) {
lc.processNonContextValues = b
})
}
// ContextValuer Control how you get the value from a field and context
type ContextValuer interface {
ContextValue(ctx *lambdacontext.LambdaContext, f LambdaField) (string, error)
}
// LambdaLogContext structure
type LambdaLogContext struct {
customBuilder ContextValuer
customNames map[LambdaField]string
ctxFields map[int]int
staticFields []zapcore.Field
fields []zapcore.Field
processNonContextValues bool
}
var emptyvalues = make([]zapcore.Field, 0)
// New Create a new LambdaLogContext
func New(options ...Option) *LambdaLogContext {
l := &LambdaLogContext{processNonContextValues: true}
if len(options) > 0 {
l.WithOptions(options...)
}
l.fields = make([]zapcore.Field, 0)
l.staticFields = make([]zapcore.Field, 0)
l.ctxFields = make(map[int]int)
return l
}
// WithOptions add these options to the context.
func (lc *LambdaLogContext) WithOptions(opts ...Option) *LambdaLogContext {
for _, v := range opts {
v.apply(lc)
}
return lc
}
// WithBasic Add basic logging context
// See ...
func (lc *LambdaLogContext) WithBasic() *LambdaLogContext {
return lc.With(AwsRequestID, FunctionName, FunctionVersion, InvokeFunctionArn, LogGroupName, LogStreamName)
}
// WithAll Add all fields to logging context
// See ...
func (lc *LambdaLogContext) WithAll() *LambdaLogContext {
return lc.WithBasic().With(CognitoIdentityID, CognitoIdentityPoolID, InstallationID, AppTitle, AppVersionCode, AppPackageName, MemoryLimitInMB)
}
func (lc *LambdaLogContext) getName(l LambdaField) string {
n, ok := lc.customNames[l]
if !ok {
return DefaultNames[l]
}
return n
}
var dummyCtx = &lambdacontext.LambdaContext{}
// With Add these fields to context Add static fields if processNonContextValues is true
func (lc *LambdaLogContext) With(fields ...LambdaField) *LambdaLogContext {
var ctxFieldIndex = len(lc.fields)
for _, f := range fields {
// fmt.Fprintln(os.Stderr, "Adding field ", f, " index ", ctxFieldIndex)
if int(f) >= staticStartIndex {
field := zap.String(lc.getName(f), Extract(dummyCtx, f))
if f == MemoryLimitInMB {
// Speical case : Memory is an int
field = zap.Int(lc.getName(f), lambdacontext.MemoryLimitInMB)
}
lc.staticFields = append(lc.staticFields, field)
if lc.processNonContextValues {
lc.ctxFields[int(f)] = ctxFieldIndex
lc.fields = append(lc.fields, field)
ctxFieldIndex++
}
} else {
lc.ctxFields[int(f)] = ctxFieldIndex
lc.fields = append(lc.fields, zap.String(lc.getName(f), ""))
ctxFieldIndex++
}
}
return lc
}
// NonContextValues e.g. lambdacontext.FunctionName or os.Getenv
func (lc *LambdaLogContext) NonContextValues() []zapcore.Field {
return lc.staticFields
}
// ContextValue get the context value for a field
func (lc *LambdaLogContext) ContextValue(ctx *lambdacontext.LambdaContext, f LambdaField) string {
if lc.customBuilder != nil {
v, err := lc.customBuilder.ContextValue(ctx, f)
if err == nil {
return v
}
}
return Extract(ctx, f)
}
// ContextValues for the lambda context.
func (lc *LambdaLogContext) ContextValues(ctx context.Context) []zapcore.Field {
lcv, ok := lambdacontext.FromContext(ctx)
if len(lc.ctxFields) == 0 || !ok {
return emptyvalues
}
for k, v := range lc.ctxFields {
if k < int(END) {
if LambdaField(k) < staticStartIndex {
lc.fields[v].String = lc.ContextValue(lcv, LambdaField(k))
}
}
if k >= 200 {
//Custom fields start at 200
lc.fields[v].String = lcv.ClientContext.Custom[lc.fields[v].Key]
}
}
return lc.fields
}
// WithEnv Add Env from os.Getenv
func (lc *LambdaLogContext) WithEnv(names ...string) *LambdaLogContext {
var start = len(lc.fields)
for _, n := range names {
lc.ctxFields[start+100] = start
f := zap.String(n, os.Getenv(n))
lc.staticFields = append(lc.staticFields, f)
lc.fields = append(lc.fields, f)
start++
}
return lc
}
// WithCustom Add names from lambdacontext.ClientContext.Custom
func (lc *LambdaLogContext) WithCustom(names ...string) *LambdaLogContext {
var start = len(lc.fields)
for _, n := range names {
lc.ctxFields[start+200] = start
lc.fields = append(lc.fields, zap.String(n, ""))
start++
}
return lc
}
// Extract a field from lambda context
func Extract(ctx *lambdacontext.LambdaContext, field LambdaField) string {
switch field {
case AwsRequestID:
return ctx.AwsRequestID
case FunctionName:
return lambdacontext.FunctionName
case FunctionVersion:
return lambdacontext.FunctionVersion
case InvokeFunctionArn:
return ctx.InvokedFunctionArn
case LogGroupName:
return lambdacontext.LogGroupName
case LogStreamName:
return lambdacontext.LogStreamName
case CognitoIdentityID:
return ctx.Identity.CognitoIdentityID
case CognitoIdentityPoolID:
return ctx.Identity.CognitoIdentityPoolID
case InstallationID:
return ctx.ClientContext.Client.InstallationID
case AppTitle:
return ctx.ClientContext.Client.AppTitle
case AppVersionCode:
return ctx.ClientContext.Client.AppVersionCode
case AppPackageName:
return ctx.ClientContext.Client.AppPackageName
default:
return ""
}
}