-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathevent_factory.go
282 lines (241 loc) · 6.25 KB
/
event_factory.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
// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package rkquery
import (
"github.com/google/uuid"
"github.com/rookie-ninja/rk-logger"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"net"
"os"
"regexp"
"runtime"
"strings"
"sync"
"time"
)
const (
goos = runtime.GOOS
goArch = runtime.GOARCH
)
var (
domain = ""
localIp = getLocalIP()
hostname = getHostName()
)
// EventOption will be pass into EventFactory while creating Event to override fields in Event.
type EventOption func(Event)
// WithZapLogger override logger in Event.
func WithZapLogger(logger *zap.Logger) EventOption {
return func(event Event) {
if logger == nil {
return
}
switch v := event.(type) {
case *eventZap:
v.logger = logger
case *eventThreadSafe:
v.delegate.logger = logger
}
}
}
// WithEncoding override encoding in Event.
func WithEncoding(ec Encoding) EventOption {
return func(event Event) {
if ec != JSON && ec != CONSOLE && ec != FLATTEN {
return
}
switch v := event.(type) {
case *eventZap:
v.encoding = ec
case *eventThreadSafe:
v.delegate.encoding = ec
}
}
}
// WithQuietMode turn on quiet mode which won't flush data to logger.
func WithQuietMode(quietMode bool) EventOption {
return func(event Event) {
switch v := event.(type) {
case *eventZap:
v.quietMode = quietMode
case *eventThreadSafe:
v.delegate.quietMode = quietMode
}
}
}
// WithEntryName override entry name in Event.
func WithEntryName(name string) EventOption {
return func(event Event) {
switch v := event.(type) {
case *eventZap:
v.entryName = name
case *eventThreadSafe:
v.delegate.entryName = name
}
}
}
// WithEntryKind override entry kind in Event.
func WithEntryKind(kind string) EventOption {
return func(event Event) {
switch v := event.(type) {
case *eventZap:
v.entryKind = kind
case *eventThreadSafe:
v.delegate.entryKind = kind
}
}
}
// WithServiceName override service name in Event.
func WithServiceName(name string) EventOption {
return func(event Event) {
switch v := event.(type) {
case *eventZap:
v.serviceName = name
case *eventThreadSafe:
v.delegate.serviceName = name
}
}
}
// WithServiceVersion overrides app version in event.
func WithServiceVersion(version string) EventOption {
return func(event Event) {
switch v := event.(type) {
case *eventZap:
v.serviceVersion = version
case *eventThreadSafe:
v.delegate.serviceVersion = version
}
}
}
// WithOperation overrides operation in Event.
func WithOperation(operation string) EventOption {
return func(event Event) {
event.SetOperation(operation)
}
}
// WithPayloads overrides payloads with form of zap.Field in Event.
func WithPayloads(fields ...zap.Field) EventOption {
return func(event Event) {
event.AddPayloads(fields...)
}
}
// EventFactory is not thread safe!!!
type EventFactory struct {
options []EventOption
}
// NewEventFactory creates a new event factory with option.
func NewEventFactory(option ...EventOption) *EventFactory {
factory := &EventFactory{
options: option,
}
domain = getDefaultIfEmptyString(os.Getenv("DOMAIN"), "*")
return factory
}
// CreateEvent creates a new event with options.
func (factory *EventFactory) CreateEvent(options ...EventOption) Event {
event := &eventZap{
logger: rklogger.EventLogger,
encoding: CONSOLE,
quietMode: false,
serviceName: "",
serviceVersion: "",
entryName: "",
entryKind: "",
eventId: generateEventId(),
traceId: "",
requestId: "",
startTime: time.Now(),
timeZone: getTimeZone(),
payloads: make([]zap.Field, 0),
errors: zapcore.NewMapObjectEncoder(),
operation: "",
remoteAddr: "localhost",
resCode: "",
status: NotStarted,
pairs: zapcore.NewMapObjectEncoder(),
counters: zapcore.NewMapObjectEncoder(),
tracker: make(map[string]*timeTracker),
}
for i := range factory.options {
opt := factory.options[i]
opt(event)
}
for i := range options {
opt := options[i]
opt(event)
}
event.logger.Core().Sync()
return event
}
// CreateEventNoop creates a new noop event.
func (factory *EventFactory) CreateEventNoop() Event {
return &eventNoop{}
}
// CreateEventThreadSafe create a new thread safe event.
func (factory *EventFactory) CreateEventThreadSafe(options ...EventOption) Event {
event := factory.CreateEvent(options...)
return &eventThreadSafe{
delegate: event.(*eventZap),
lock: &sync.Mutex{},
}
}
// Get hostname of current machine.
func getHostName() string {
hostName, err := os.Hostname()
// In this version, we will ignore errors returned by OS
if err != nil {
hostName = unknown
}
return hostName
}
// Generate request id based on google/uuid.
// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services.
//
// A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to maps or compared directly.
func generateEventId() string {
// do not use uuid.New() since it would panic if any error occurs
requestId, err := uuid.NewRandom()
// currently, we will return empty string if error occurs
if err != nil {
return ""
}
return requestId.String()
}
// Get time zone.
func getTimeZone() string {
zone, _ := time.Now().Zone()
return zone
}
// Return default value if original string is empty.
func getDefaultIfEmptyString(origin, def string) string {
if len(origin) < 1 {
return def
}
return origin
}
// This is a tricky function.
// We will iterate through all the network interfaces,but will choose the first one since we are assuming that
// eth0 will be the default one to use in most of the case.
//
// Currently, we do not have any interfaces for selecting the network interface yet.
func getLocalIP() string {
localIP := "localhost"
// skip the error since we don't want to break RPC calls because of it
addresses, err := net.InterfaceAddrs()
if err != nil {
return localIP
}
for _, addr := range addresses {
items := strings.Split(addr.String(), "/")
if len(items) < 2 || items[0] == "127.0.0.1" {
continue
}
if match, err := regexp.MatchString(`\d+\.\d+\.\d+\.\d+`, items[0]); err == nil && match {
localIP = items[0]
}
}
return localIP
}