-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathTelemetryClient.ts
272 lines (242 loc) · 11.4 KB
/
TelemetryClient.ts
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
import url = require("url");
import os = require("os");
import Config = require("./Config");
import AuthorizationHandler = require("./AuthorizationHandler");
import Context = require("./Context");
import Contracts = require("../Declarations/Contracts");
import Channel = require("./Channel");
import TelemetryProcessors = require("../TelemetryProcessors");
import { CorrelationContextManager } from "../AutoCollection/CorrelationContextManager";
import Statsbeat = require("../AutoCollection/Statsbeat");
import Sender = require("./Sender");
import Util = require("./Util");
import Logging = require("./Logging");
import FlushOptions = require("./FlushOptions");
import EnvelopeFactory = require("./EnvelopeFactory");
import QuickPulseStateManager = require("./QuickPulseStateManager");
import { Tags } from "../Declarations/Contracts";
/**
* Application Insights telemetry client provides interface to track telemetry items, register telemetry initializers and
* and manually trigger immediate sending (flushing)
*/
class TelemetryClient {
private static TAG = "TelemetryClient";
private _telemetryProcessors: { (envelope: Contracts.EnvelopeTelemetry, contextObjects: { [name: string]: any; }): boolean; }[] = [];
private _statsbeat: Statsbeat | undefined;
public config: Config;
public context: Context;
public commonProperties: { [key: string]: string; };
public channel: Channel;
public quickPulseClient: QuickPulseStateManager;
public authorizationHandler: AuthorizationHandler;
/**
* Constructs a new client of the client
* @param setupString the Connection String or Instrumentation Key to use (read from environment variable if not specified)
*/
constructor(setupString?: string) {
var config = new Config(setupString);
this.config = config;
if (!this.config.instrumentationKey || this.config.instrumentationKey == "") {
throw new Error("Instrumentation key not found, please provide a connection string before starting Application Insights SDK.");
}
this.context = new Context();
this.commonProperties = {};
this.authorizationHandler = null;
if (!this.config.disableStatsbeat) {
this._statsbeat = new Statsbeat(this.config, this.context);
this._statsbeat.enable(true);
}
var sender = new Sender(this.config, this.getAuthorizationHandler, null, null, this._statsbeat);
this.channel = new Channel(() => config.disableAppInsights, () => config.maxBatchSize, () => config.maxBatchIntervalMs, sender);
}
/**
* Log information about availability of an application
* @param telemetry Object encapsulating tracking options
*/
public trackAvailability(telemetry: Contracts.AvailabilityTelemetry): void {
this.track(telemetry, Contracts.TelemetryType.Availability);
}
/**
* Log a page view
* @param telemetry Object encapsulating tracking options
*/
public trackPageView(telemetry: Contracts.PageViewTelemetry): void {
this.track(telemetry, Contracts.TelemetryType.PageView);
}
/**
* Log a trace message
* @param telemetry Object encapsulating tracking options
*/
public trackTrace(telemetry: Contracts.TraceTelemetry): void {
this.track(telemetry, Contracts.TelemetryType.Trace);
}
/**
* Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.
* To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the
* telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals.
* @param telemetry Object encapsulating tracking options
*/
public trackMetric(telemetry: Contracts.MetricTelemetry): void {
this.track(telemetry, Contracts.TelemetryType.Metric);
}
/**
* Log an exception
* @param telemetry Object encapsulating tracking options
*/
public trackException(telemetry: Contracts.ExceptionTelemetry): void {
if (telemetry && telemetry.exception && !Util.isError(telemetry.exception)) {
telemetry.exception = new Error(telemetry.exception.toString());
}
this.track(telemetry, Contracts.TelemetryType.Exception);
}
/**
* Log a user action or other occurrence.
* @param telemetry Object encapsulating tracking options
*/
public trackEvent(telemetry: Contracts.EventTelemetry): void {
this.track(telemetry, Contracts.TelemetryType.Event);
}
/**
* Log a request. Note that the default client will attempt to collect HTTP requests automatically so only use this for requests
* that aren't automatically captured or if you've disabled automatic request collection.
*
* @param telemetry Object encapsulating tracking options
*/
public trackRequest(telemetry: Contracts.RequestTelemetry & Contracts.Identified): void {
this.track(telemetry, Contracts.TelemetryType.Request);
}
/**
* Log a dependency. Note that the default client will attempt to collect dependencies automatically so only use this for dependencies
* that aren't automatically captured or if you've disabled automatic dependency collection.
*
* @param telemetry Object encapsulating tracking option
* */
public trackDependency(telemetry: Contracts.DependencyTelemetry & Contracts.Identified) {
if (telemetry && !telemetry.target && telemetry.data) {
// url.parse().host returns null for non-urls,
// making this essentially a no-op in those cases
// If this logic is moved, update jsdoc in DependencyTelemetry.target
// url.parse() is deprecated, update to use WHATWG URL API instead
try {
telemetry.target = new url.URL(telemetry.data).host;
} catch (error) {
// set target as null to be compliant with previous behavior
telemetry.target = null;
Logging.warn(TelemetryClient.TAG, "The URL object is failed to create.", error);
}
}
this.track(telemetry, Contracts.TelemetryType.Dependency);
}
/**
* Immediately send all queued telemetry.
* @param options Flush options, including indicator whether app is crashing and callback
*/
public flush(options?: FlushOptions) {
this.channel.triggerSend(
options ? !!options.isAppCrashing : false,
options ? options.callback : undefined);
}
/**
* Generic track method for all telemetry types
* @param data the telemetry to send
* @param telemetryType specify the type of telemetry you are tracking from the list of Contracts.DataTypes
*/
public track(telemetry: Contracts.Telemetry, telemetryType: Contracts.TelemetryType) {
if (telemetry && Contracts.telemetryTypeToBaseType(telemetryType)) {
var envelope = EnvelopeFactory.createEnvelope(telemetry, telemetryType, this.commonProperties, this.context, this.config);
// Set time on the envelope if it was set on the telemetry item
if (telemetry.time) {
envelope.time = telemetry.time.toISOString();
}
var accepted = this.runTelemetryProcessors(envelope, telemetry.contextObjects);
// Ideally we would have a central place for "internal" telemetry processors and users can configure which ones are in use.
// This will do for now. Otherwise clearTelemetryProcessors() would be problematic.
accepted = accepted && TelemetryProcessors.samplingTelemetryProcessor(envelope, { correlationContext: CorrelationContextManager.getCurrentContext() });
TelemetryProcessors.preAggregatedMetricsTelemetryProcessor(envelope, this.context);
if (accepted) {
TelemetryProcessors.performanceMetricsTelemetryProcessor(envelope, this.quickPulseClient);
this.channel.send(envelope);
}
}
else {
Logging.warn(TelemetryClient.TAG, "track() requires telemetry object and telemetryType to be specified.")
}
}
/**
* @deprecated The method should not be called, Azure Properties will be added always when available
* Automatically populate telemetry properties like RoleName when running in Azure
*
* @param value if true properties will be populated
*/
public setAutoPopulateAzureProperties(value: boolean) {
// NO-OP
}
/**
* Get Authorization handler
*/
public getAuthorizationHandler(config: Config): AuthorizationHandler {
if (config && config.aadTokenCredential) {
if (!this.authorizationHandler) {
Logging.info(TelemetryClient.TAG, "Adding authorization handler");
this.authorizationHandler = new AuthorizationHandler(config.aadTokenCredential, config.aadAudience);
}
return this.authorizationHandler;
}
return null;
}
/**
* Adds telemetry processor to the collection. Telemetry processors will be called one by one
* before telemetry item is pushed for sending and in the order they were added.
*
* @param telemetryProcessor function, takes Envelope, and optional context object and returns boolean
*/
public addTelemetryProcessor(telemetryProcessor: (envelope: Contracts.EnvelopeTelemetry, contextObjects?: { [name: string]: any; }) => boolean) {
this._telemetryProcessors.push(telemetryProcessor);
}
/*
* Removes all telemetry processors
*/
public clearTelemetryProcessors() {
this._telemetryProcessors = [];
}
private runTelemetryProcessors(envelope: Contracts.EnvelopeTelemetry, contextObjects: { [name: string]: any; }): boolean {
var accepted = true;
var telemetryProcessorsCount = this._telemetryProcessors.length;
if (telemetryProcessorsCount === 0) {
return accepted;
}
contextObjects = contextObjects || {};
contextObjects["correlationContext"] = CorrelationContextManager.getCurrentContext();
for (var i = 0; i < telemetryProcessorsCount; ++i) {
try {
var processor = this._telemetryProcessors[i];
if (processor) {
if (processor.apply(null, [envelope, contextObjects]) === false) {
accepted = false;
break;
}
}
} catch (error) {
accepted = true;
Logging.warn(TelemetryClient.TAG, "One of telemetry processors failed, telemetry item will be sent.", error, envelope);
}
}
// Sanitize tags and properties after running telemetry processors
if (accepted) {
if (envelope && envelope.tags) {
envelope.tags = Util.validateStringMap(envelope.tags) as Tags & Tags[];
}
if (envelope && envelope.data && envelope.data.baseData && envelope.data.baseData.properties) {
envelope.data.baseData.properties = Util.validateStringMap(envelope.data.baseData.properties);
}
}
return accepted;
}
/*
* Get Statsbeat instance
*/
public getStatsbeat() {
return this._statsbeat;
}
}
export = TelemetryClient;