-
Notifications
You must be signed in to change notification settings - Fork 0
/
xtelemetry.go
271 lines (238 loc) · 9.88 KB
/
xtelemetry.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
package telemetry
import (
"context"
"time"
"github.com/microsoft/ApplicationInsights-Go/appinsights"
"github.com/microsoft/ApplicationInsights-Go/appinsights/contracts"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type XTelemetryObject interface {
Debug(ctx context.Context, message string, fields ...XField)
Info(ctx context.Context, message string, fields ...XField)
Warn(ctx context.Context, message string, fields ...XField)
Error(ctx context.Context, message string, fields ...XField)
Dependency(ctx context.Context, dependencyType string, target string, success bool, startTime time.Time, endTime time.Time, message string, fields ...XField)
Request(ctx context.Context, method string, url string, duration time.Duration, responseCode string, success bool, source string, message string, fields ...XField)
}
// XTelemetryObjectImpl will store the logger, the app insights client and the service name
type XTelemetryObjectImpl struct {
logger *zap.Logger
appinsights appinsights.TelemetryClient
xConfig XTelemetryConfig
}
// Initialize the telemetry object
func NewXTelemetry(cc XTelemetryConfig) (*XTelemetryObjectImpl, error) {
// Define configuration for the logger
zapconfig := zap.Config{
Development: false,
Encoding: "json",
EncoderConfig: zapcore.EncoderConfig{
TimeKey: "ts",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.EpochTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
},
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stderr"},
}
// Set the log level
switch cc.GetLogLevel() {
case "debug":
zapconfig.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
case "info":
zapconfig.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
case "warn":
zapconfig.Level = zap.NewAtomicLevelAt(zap.WarnLevel)
case "error":
zapconfig.Level = zap.NewAtomicLevelAt(zap.ErrorLevel)
default:
zapconfig.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
}
// Create a new logger, with the provided caller skip (1 would skip the current frame, since we are in the telemetry package)
logger, err := zapconfig.Build(zap.AddCallerSkip(cc.GetCallerSkip()))
if err != nil {
return nil, err
}
// Initialize App Insights client, skip initialization if instrumentation key is not provided
var appInsightsClient appinsights.TelemetryClient
if cc.GetInstrumentationKey() != "" {
// Initialize telemetry client
appInsightsClient = appinsights.NewTelemetryClient(cc.GetInstrumentationKey())
// Set the role name
appInsightsClient.Context().Tags.Cloud().SetRole(cc.GetServiceName())
}
return &XTelemetryObjectImpl{
logger: logger,
appinsights: appInsightsClient,
xConfig: cc,
}, nil
}
// Debug will log the message using xTelemetry (no trace to App Insights)
func (t *XTelemetryObjectImpl) Debug(ctx context.Context, message string, fields ...XField) {
t.logger.Debug(message, convertFields(fields)...)
}
// Info will log the message using xTelemetry and also send a trace to App Insights
func (t *XTelemetryObjectImpl) Info(ctx context.Context, message string, fields ...XField) {
// Get the operation ID from the context
operationID, ok := ctx.Value(OperationIDKeyContextKey).(string)
if !ok {
operationID = ""
}
// Create the new log trace
telemFields := convertFields(fields)
telemFields = append(telemFields, zap.String(string(ServiceNameContextKey), t.xConfig.GetServiceName()))
if operationID != "" {
telemFields = append(telemFields, zap.String(string(OperationIDKeyContextKey), operationID))
}
t.logger.Info(message, telemFields...)
// Create the new trace in App Insights, if the client is initialized
if t.appinsights != nil {
// Create the new trace
trace := appinsights.NewTraceTelemetry(constructTraceMessage(t.xConfig.GetServiceName(), operationID, message), contracts.Information)
// Add properties to App Insights trace
for _, field := range fields {
trace.Properties[field.Key] = field.Value.(string)
}
// Set parent id, using the operationID from the context
if operationID != "" {
trace.Tags.Operation().SetParentId(operationID)
trace.Properties[string(OperationIDKeyContextKey)] = operationID
}
// Add service name as a property
trace.Properties[string(ServiceNameContextKey)] = t.xConfig.GetServiceName()
// Send the trace to App Insights
t.appinsights.Track(trace)
}
}
// Warn will log the message using xTelemetry and also send a trace to App Insights
// TODO
func (t *XTelemetryObjectImpl) Warn(ctx context.Context, message string, fields ...XField) {
t.logger.Warn(message, convertFields(fields)...)
}
// Error will log the message using xTelemetry and also send an exception to App Insights
func (t *XTelemetryObjectImpl) Error(ctx context.Context, message string, fields ...XField) {
// Get the operation ID from the context
operationID, ok := ctx.Value(OperationIDKeyContextKey).(string)
if !ok {
operationID = ""
}
// Create the new error trace
telemFields := convertFields(fields)
telemFields = append(telemFields, zap.String(string(ServiceNameContextKey), t.xConfig.GetServiceName()))
if operationID != "" {
telemFields = append(telemFields, zap.String(string(OperationIDKeyContextKey), operationID))
}
t.logger.Error(message, telemFields...)
// Create the new exception in App Insights, if the client is initialized
if t.appinsights != nil {
// Create the new exception
exception := appinsights.NewExceptionTelemetry(constructTraceMessage(t.xConfig.GetServiceName(), operationID, message))
exception.SeverityLevel = contracts.Error
// Add properties to the exception
for _, field := range fields {
exception.Properties[field.Key] = field.Value.(string)
}
// Set parent id, using the operationID from the context
if operationID != "" {
exception.Tags.Operation().SetParentId(operationID)
exception.Properties[string(OperationIDKeyContextKey)] = operationID
}
// Add service name as a property
exception.Properties[string(ServiceNameContextKey)] = t.xConfig.GetServiceName()
t.appinsights.Track(exception)
}
}
// Dependency will log the dependency using xTelemetry and also send a dependency to App Insights
func (t *XTelemetryObjectImpl) Dependency(ctx context.Context, dependencyType string, target string, success bool, startTime time.Time, endTime time.Time, message string, fields ...XField) {
// Get the operation ID from the context
operationID, ok := ctx.Value(OperationIDKeyContextKey).(string)
if !ok {
operationID = ""
}
// Create an info trace
telemFields := convertFields(fields)
telemFields = append(telemFields, zap.String(string(ServiceNameContextKey), t.xConfig.GetServiceName()))
if operationID != "" {
telemFields = append(telemFields, zap.String(string(OperationIDKeyContextKey), operationID))
}
t.logger.Info(message, telemFields...)
// Create the new dependency in App Insights, if the client is initialized
if t.appinsights != nil {
// Create the new dependency
dependency := appinsights.NewRemoteDependencyTelemetry(constructTraceMessage(t.xConfig.GetServiceName(), operationID, message), dependencyType, target, success)
dependency.MarkTime(startTime, endTime)
// Add properties to the dependency
for _, field := range fields {
dependency.Properties[field.Key] = field.Value.(string)
}
// Set parent id, using the operationID from the context
if operationID != "" {
dependency.Tags.Operation().SetParentId(operationID)
dependency.Properties[string(OperationIDKeyContextKey)] = operationID
}
// Add service name as a property
dependency.Properties[string(ServiceNameContextKey)] = t.xConfig.GetServiceName()
t.appinsights.Track(dependency)
}
}
// Request will log the request using xTelemetry and also send a request to App Insights
func (t *XTelemetryObjectImpl) Request(ctx context.Context, method string, url string, startTime time.Time, endTime time.Time, responseCode string, success bool, source string, message string, fields ...XField) {
// Calculate the duration
duration := endTime.Sub(startTime)
// Get the operation ID from the context
operationID, ok := ctx.Value(OperationIDKeyContextKey).(string)
if !ok {
operationID = ""
}
// Create an info trace
telemFields := convertFields(fields)
telemFields = append(telemFields, zap.String(string(ServiceNameContextKey), t.xConfig.GetServiceName()))
if operationID != "" {
telemFields = append(telemFields, zap.String(string(OperationIDKeyContextKey), operationID))
}
t.logger.Info(message, telemFields...)
// Create the new request in App Insights, if the client is initialized
if t.appinsights != nil {
// Create the new request
request := appinsights.NewRequestTelemetry(method, url, duration, responseCode)
request.MarkTime(startTime, endTime)
request.Source = source
request.Success = success
// Add properties to the request
for _, field := range fields {
request.Properties[field.Key] = field.Value.(string)
}
// Append the operation ID to the request properties
if operationID != "" {
request.Tags.Operation().SetId(operationID)
request.Properties[string(OperationIDKeyContextKey)] = operationID
}
// Add service name as a property
request.Properties[string(ServiceNameContextKey)] = t.xConfig.GetServiceName()
t.appinsights.Track(request)
}
}
// Convert the telemetry property fields to zap fields
func convertFields(fields []XField) []zap.Field {
zapFields := make([]zap.Field, len(fields))
for i, field := range fields {
zapFields[i] = zap.Any(field.Key, field.Value)
}
return zapFields
}
// Helper function to construct the trace message
func constructTraceMessage(serviceName string, operationID string, message string) string {
if operationID == "" {
return serviceName + "::" + message
} else {
return serviceName + "::" + operationID + "::" + message
}
}