Repository navigation
Expand file tree
/
Copy pathLogging.ts
More file actions
299 lines (263 loc) · 10.8 KB
/
Copy pathLogging.ts
File metadata and controls
299 lines (263 loc) · 10.8 KB
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
module Microsoft.ApplicationInsights {
export enum LoggingSeverity {
/**
* Error will be sent as internal telemetry
*/
CRITICAL = 0,
/**
* Error will NOT be sent as internal telemetry, and will only be shown in browser console
*/
WARNING = 1
}
/**
* Internal message ID. Please create a new one for every conceptually different message. Please keep alphabetically ordered
*/
export enum _InternalMessageId {
// Non user actionable
BrowserDoesNotSupportLocalStorage,
BrowserCannotReadLocalStorage,
BrowserCannotReadSessionStorage,
BrowserCannotWriteLocalStorage,
BrowserCannotWriteSessionStorage,
BrowserFailedRemovalFromLocalStorage,
BrowserFailedRemovalFromSessionStorage,
CannotSendEmptyTelemetry,
ClientPerformanceMathError,
ErrorParsingAISessionCookie,
ErrorPVCalc,
ExceptionWhileLoggingError,
FailedAddingTelemetryToBuffer,
FailedMonitorAjaxAbort,
FailedMonitorAjaxDur,
FailedMonitorAjaxOpen,
FailedMonitorAjaxRSC,
FailedMonitorAjaxSend,
FailedMonitorAjaxGetCorrelationHeader,
FailedToAddHandlerForOnBeforeUnload,
FailedToSendQueuedTelemetry,
FailedToReportDataLoss,
FlushFailed,
MessageLimitPerPVExceeded,
MissingRequiredFieldSpecification,
NavigationTimingNotSupported,
OnError,
SessionRenewalDateIsZero,
SenderNotInitialized,
StartTrackEventFailed,
StopTrackEventFailed,
StartTrackFailed,
StopTrackFailed,
TelemetrySampledAndNotSent,
TrackEventFailed,
TrackExceptionFailed,
TrackMetricFailed,
TrackPVFailed,
TrackPVFailedCalc,
TrackTraceFailed,
TransmissionFailed,
FailedToSetStorageBuffer,
FailedToRestoreStorageBuffer,
InvalidBackendResponse,
FailedToFixDepricatedValues,
InvalidDurationValue,
// User actionable
CannotSerializeObject,
CannotSerializeObjectNonSerializable,
CircularReferenceDetected,
ClearAuthContextFailed,
ExceptionTruncated,
IllegalCharsInName,
ItemNotInArray,
MaxAjaxPerPVExceeded,
MessageTruncated,
NameTooLong,
SampleRateOutOfRange,
SetAuthContextFailed,
SetAuthContextFailedAccountName,
StringValueTooLong,
StartCalledMoreThanOnce,
StopCalledWithoutStart,
TelemetryInitializerFailed,
TrackArgumentsNotSpecified,
UrlTooLong,
SessionStorageBufferFull,
CannotAccessCookie,
IdTooLong,
}
export class _InternalLogMessage {
public message: string;
public messageId: _InternalMessageId;
/**
* For user non actionable traces use AI Internal prefix.
*/
private static AiNonUserActionablePrefix = "AI (Internal): ";
/**
* Prefix of the traces in portal.
*/
private static AiUserActionablePrefix = "AI: ";
constructor(msgId: _InternalMessageId, msg: string, isUserAct = false, properties?: Object) {
this.messageId = msgId;
this.message =
(isUserAct ? _InternalLogMessage.AiUserActionablePrefix : _InternalLogMessage.AiNonUserActionablePrefix) +
_InternalMessageId[msgId].toString();
var diagnosticText =
(msg ? " message:" + _InternalLogMessage.sanitizeDiagnosticText(msg) : "") +
(properties ? " props:" + _InternalLogMessage.sanitizeDiagnosticText(JSON.stringify(properties)) : "");
this.message += diagnosticText;
}
private static sanitizeDiagnosticText(text: string) {
return "\"" + text.replace(/\"/g, "") + "\"";
}
}
export class _InternalLogging {
/**
* Session storage key for the prefix for the key indicating message type already logged
*/
private static AIInternalMessagePrefix: string = "AITR_";
/**
* When this is true the SDK will throw exceptions to aid in debugging.
*/
public static enableDebugExceptions = () => false;
/**
* When this is true the SDK will log more messages to aid in debugging.
*/
public static verboseLogging = () => false;
/**
* The internal logging queue
*/
public static queue: Array<_InternalLogMessage> = [];
/**
* The maximum number of internal messages allowed to be sent per page view
*/
private static MAX_INTERNAL_MESSAGE_LIMIT = 25;
/**
* Count of internal messages sent
*/
private static _messageCount = 0;
/**
* Holds information about what message types were already logged to console or sent to server.
*/
private static _messageLogged: { [type: string]: boolean } = {};
/**
* This method will throw exceptions in debug mode or attempt to log the error as a console warning.
* @param severity {LoggingSeverity} - The severity of the log message
* @param message {_InternalLogMessage} - The log message.
*/
public static throwInternal(severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct = false) {
let message = new _InternalLogMessage(msgId, msg, isUserAct, properties);
if (this.enableDebugExceptions()) {
throw message;
} else {
if (typeof (message) !== "undefined" && !!message) {
if (typeof (message.message) !== "undefined") {
if (isUserAct) {
// check if this message type was already logged to console for this page view and if so, don't log it again
var messageKey = _InternalMessageId[message.messageId];
if (!this._messageLogged[messageKey] || this.verboseLogging()) {
this.warnToConsole(message.message);
this._messageLogged[messageKey] = true;
}
} else {
// don't log internal AI traces in the console, unless the verbose logging is enabled
if (this.verboseLogging()) {
this.warnToConsole(message.message);
}
}
this.logInternalMessage(severity, message);
}
}
}
}
/**
* This will write a warning to the console if possible
* @param message {string} - The warning message
*/
public static warnToConsole(message: string) {
if (typeof console !== "undefined" && !!console) {
if (typeof console.warn === "function") {
console.warn(message);
} else if (typeof console.log === "function") {
console.log(message);
}
}
}
/**
* Resets the internal message count
*/
public static resetInternalMessageCount(): void {
this._messageCount = 0;
this._messageLogged = {};
}
/**
* Clears the list of records indicating that internal message type was already logged
*/
public static clearInternalMessageLoggedTypes(): void {
if (Util.canUseSessionStorage()) {
var sessionStorageKeys = Util.getSessionStorageKeys();
for (var i = 0; i < sessionStorageKeys.length; i++) {
if (sessionStorageKeys[i].indexOf(_InternalLogging.AIInternalMessagePrefix) === 0) {
Util.removeSessionStorage(sessionStorageKeys[i]);
}
}
}
}
/**
* Sets the limit for the number of internal events before they are throttled
* @param limit {number} - The throttle limit to set for internal events
*/
public static setMaxInternalMessageLimit(limit: number): void {
if (!limit) {
throw new Error('limit cannot be undefined.');
}
this.MAX_INTERNAL_MESSAGE_LIMIT = limit;
}
/**
* Logs a message to the internal queue.
* @param severity {LoggingSeverity} - The severity of the log message
* @param message {_InternalLogMessage} - The message to log.
*/
private static logInternalMessage(severity: LoggingSeverity, message: _InternalLogMessage): void {
if (this._areInternalMessagesThrottled()) {
return;
}
// check if this message type was already logged for this session and if so, don't log it again
var logMessage = true;
var messageKey = _InternalLogging.AIInternalMessagePrefix + _InternalMessageId[message.messageId];
if (Util.canUseSessionStorage()) {
var internalMessageTypeLogRecord = Util.getSessionStorage(messageKey);
if (internalMessageTypeLogRecord) {
logMessage = false;
} else {
Util.setSessionStorage(messageKey, "1");
}
} else {
// if the session storage is not available, limit to only one message type per page view
if (this._messageLogged[messageKey]) {
logMessage = false;
} else {
this._messageLogged[messageKey] = true;
}
}
if (logMessage) {
// Push the event in the internal queue
if (this.verboseLogging() || severity === LoggingSeverity.CRITICAL) {
this.queue.push(message);
this._messageCount++;
}
// When throttle limit reached, send a special event
if (this._messageCount == this.MAX_INTERNAL_MESSAGE_LIMIT) {
var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app.";
var throttleMessage = new _InternalLogMessage(_InternalMessageId.MessageLimitPerPVExceeded, throttleLimitMessage, false);
this.queue.push(throttleMessage);
this.warnToConsole(throttleLimitMessage);
}
}
}
/**
* Indicates whether the internal events are throttled
*/
private static _areInternalMessagesThrottled(): boolean {
return this._messageCount >= this.MAX_INTERNAL_MESSAGE_LIMIT;
}
}
}