/
TelemetryClient.ts
212 lines (183 loc) · 8.56 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
import url = require("url");
import os = require("os");
import Config = require("./Config");
import Context = require("./Context");
import Contracts = require("../Declarations/Contracts");
import Channel = require("./Channel");
import TelemetryProcessors = require("../TelemetryProcessors");
import { CorrelationContextManager } from "../AutoCollection/CorrelationContextManager";
import Sender = require("./Sender");
import Util = require("./Util");
import Logging = require("./Logging");
import FlushOptions = require("./FlushOptions");
import EnvelopeFactory = require("./EnvelopeFactory");
import QuickPulseStateManager = require("./QuickPulseStateManager");
/**
* Application Insights telemetry client provides interface to track telemetry items, register telemetry initializers and
* and manually trigger immediate sending (flushing)
*/
class TelemetryClient {
private _telemetryProcessors: { (envelope: Contracts.Envelope, contextObjects: { [name: string]: any; }): boolean; }[] = [];
public config: Config;
public context: Context;
public commonProperties: { [key: string]: string; };
public channel: Channel;
public quickPulseClient: QuickPulseStateManager;
/**
* 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;
this.context = new Context();
this.commonProperties = {};
var sender = new Sender(this.config);
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): 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) {
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
telemetry.target = url.parse(telemetry.data).host;
}
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() });
if (accepted) {
TelemetryProcessors.performanceMetricsTelemetryProcessor(envelope, this.quickPulseClient);
this.channel.send(envelope);
}
}
else {
Logging.warn("track() requires telemetry object and telemetryType to be specified.")
}
}
/**
* 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.Envelope, contextObjects?: { [name: string]: any; }) => boolean) {
this._telemetryProcessors.push(telemetryProcessor);
}
/*
* Removes all telemetry processors
*/
public clearTelemetryProcessors() {
this._telemetryProcessors = [];
}
private runTelemetryProcessors(envelope: Contracts.Envelope, 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("One of telemetry processors failed, telemetry item will be sent.", error, envelope);
}
}
return accepted;
}
}
export = TelemetryClient;