@azure/monitor-opentelemetry 1.0.0-beta.0 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Azure Monitor OpenTelemetry client library for JavaScript
1
+ # Azure Monitor OpenTelemetry for JavaScript
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/%40azure%2Fmonitor-opentelemetry.svg)](https://badge.fury.io/js/%40azure%2Fmonitor-opentelemetry)
4
4
 
@@ -12,6 +12,8 @@
12
12
 
13
13
  - [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
14
14
 
15
+ - [OpenTelemetry supported runtimes](https://github.com/open-telemetry/opentelemetry-js#supported-runtimes)
16
+
15
17
  See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details.
16
18
 
17
19
  ### Prerequisites
@@ -21,11 +23,11 @@ See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUP
21
23
 
22
24
  ### Enable Azure Monitor OpenTelemetry Client
23
25
 
24
- > *Important:* `AzureMonitorOpenTelemetryClient` must be setup *and* started *before* you import anything else. There may be resulting telemetry loss if other libraries are imported first.
26
+ > *Important:* `useAzureMonitor` must be called *before* you import anything else. There may be resulting telemetry loss if other libraries are imported first.
25
27
 
26
28
 
27
29
  ```typescript
28
- const { AzureMonitorOpenTelemetryClient, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
30
+ const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
29
31
 
30
32
  const options: AzureMonitorOpenTelemetryOptions = {
31
33
  azureMonitorExporterConfig: {
@@ -33,34 +35,371 @@ const options: AzureMonitorOpenTelemetryOptions = {
33
35
  process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
34
36
  },
35
37
  }
36
- const client = new AzureMonitorOpenTelemetryClient(options);
38
+ useAzureMonitor(options);
37
39
  ```
38
40
 
39
41
  * Connection String could be set using the environment variable APPLICATIONINSIGHTS\_CONNECTION\_STRING
40
42
 
41
- ## Examples
43
+ ## Configuration
42
44
 
43
- For complete samples of a few champion scenarios, see the [`samples/`](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/monitor/monitor-opentelemetry/samples-dev/) folder.
44
45
 
45
- ## Key concepts
46
+ ```typescript
47
+ const { AzureMonitorOpenTelemetryClient, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
48
+ const { Resource } = require("@opentelemetry/resources");
46
49
 
47
- For more information on the OpenTelemetry project, please review the [**OpenTelemetry Specifications**](https://github.com/open-telemetry/opentelemetry-specification#opentelemetry-specification).
50
+ const resource = new Resource({ "testAttribute": "testValue" });
51
+ const options: AzureMonitorOpenTelemetryOptions = {
52
+ azureMonitorExporterConfig: {
53
+ // Offline storage
54
+ storageDirectory: "c://azureMonitor",
55
+ // Automatic retries
56
+ disableOfflineStorage: false,
57
+ // Application Insights Connection String
58
+ connectionString: process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
59
+ },
60
+ otlpTraceExporterConfig: {
61
+ enabled: true,
62
+ url: '<opentelemetry-collector-url>', // url is optional and can be omitted - default is http://localhost:4318/v1/traces
63
+ },
64
+ otlpMetricExporterConfig: {
65
+ enabled: true,
66
+ url: '<opentelemetry-collector-url>', // url is optional and can be omitted - default is http://localhost:4318/v1/metrics
67
+ },
68
+ otlpLogExporterConfig: {
69
+ enabled: true,
70
+ url: '<opentelemetry-collector-url>', // url is optional and can be omitted - default is http://localhost:4318/v1/logs
71
+ },
72
+ samplingRatio: 1,
73
+ instrumentationOptions: {
74
+ azureSdk: { enabled: true },
75
+ http: { enabled: true },
76
+ mongoDb: { enabled: true },
77
+ mySql: { enabled: true },
78
+ postgreSql: { enabled: true },
79
+ redis: { enabled: true },
80
+ redis4: { enabled: true },
81
+ },
82
+ resource: resource
83
+ };
48
84
 
49
- ## Troubleshooting
85
+ useAzureMonitor(options);
86
+
87
+ ```
88
+
89
+
90
+ |Property|Description|Default|
91
+ | ------------------------------- |------------------------------------------------------------------------------------------------------------|-------|
92
+ | azureMonitorExporterConfig | Azure Monitor OpenTelemetry Exporter Configuration. [More info here](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/monitor/monitor-opentelemetry-exporter) | |
93
+ | otlpTraceExporterConfig | OTLP Trace Exporter Configuration. [More info here](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/exporter-trace-otlp-http)
94
+ | otlpMetricExporterConfig | OTLP Trace Exporter Configuration. [More info here](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-exporter-metrics-otlp-http)
95
+ | otlpLogExporterConfig | OTLP Trace Exporter Configuration. [More info here](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/exporter-logs-otlp-http) | |
96
+ | samplingRatio | Sampling ratio must take a value in the range [0,1], 1 meaning all data will sampled and 0 all Tracing data will be sampled out. | 1|
97
+ | instrumentationOptions| Allow configuration of OpenTelemetry Instrumentations. | {"http": { enabled: true },"azureSdk": { enabled: false },"mongoDb": { enabled: false },"mySql": { enabled: false },"postgreSql": { enabled: false },"redis": { enabled: false }}|
98
+ | resource | Opentelemetry Resource. [More info here](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-resources) ||
99
+
100
+ Options could be set using configuration file `applicationinsights.json` located under root folder of @azure/monitor-opentelemetry package installation folder, Ex: `node_modules/@azure/monitor-opentelemetry`. These configuration values will be applied to all AzureMonitorOpenTelemetryClient instances.
101
+
102
+
103
+ ```json
104
+ {
105
+ "samplingRatio": 0.8,
106
+ "enableAutoCollectStandardMetrics": false,
107
+ "instrumentationOptions":{
108
+ "azureSdk": {
109
+ "enabled": false
110
+ }
111
+ },
112
+ ...
113
+ }
114
+
115
+ ```
116
+
117
+ Custom JSON file could be provided using `APPLICATIONINSIGHTS_CONFIGURATION_FILE` environment variable.
118
+
119
+ ```javascript
120
+ process.env.APPLICATIONINSIGHTS_CONFIGURATION_FILE = "C:/applicationinsights/config/customConfig.json"
121
+
122
+ // Application Insights SDK setup....
123
+ ```
124
+
125
+ ## Instrumentation libraries
126
+
127
+ The following OpenTelemetry Instrumentation libraries are included as part of Azure Monitor OpenTelemetry.
128
+
129
+ > *Warning:* Instrumentation libraries are based on experimental OpenTelemetry specifications. Microsoft's *preview* support commitment is to ensure that the following libraries emit data to Azure Monitor Application Insights, but it's possible that breaking changes or experimental mapping will block some data elements.
130
+
131
+ ### Distributed Tracing
132
+
133
+ - [HTTP/HTTPS](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http)
134
+ - [MongoDB](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-mongodb)
135
+ - [MySQL](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-mysql)
136
+ - [Postgres](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-pg)
137
+ - [Redis](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-redis)
138
+ - [Redis-4](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-redis-4)
139
+ - [Azure SDK](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/instrumentation/opentelemetry-instrumentation-azure-sdk)
50
140
 
51
- ### Enable debug logging
141
+ ### Metrics
142
+ - [HTTP/HTTPS](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http)
52
143
 
53
- You can enable debug logging by changing the logging level of your provider.
144
+ Other OpenTelemetry Instrumentations are available [here](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node) and could be added using TracerProvider in AzureMonitorOpenTelemetryClient.
54
145
 
55
- ```js
56
- const { DiagConsoleLogger, DiagLogLevel, diag } = require("@opentelemetry/api");
146
+ ```typescript
147
+ const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
148
+ const { metrics, trace } = require("@opentelemetry/api");
149
+ const { registerInstrumentations } = require("@opentelemetry/instrumentation");
150
+ const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
151
+
152
+ useAzureMonitor();
153
+ const instrumentations = [
154
+ new ExpressInstrumentation(),
155
+ ];
156
+ registerInstrumentations({
157
+ tracerProvider: trace.getTracerProvider(),
158
+ meterProvider: metrics.getMeterProvider(),
159
+ instrumentations: instrumentations,
160
+ });
161
+
162
+ ```
163
+
164
+
165
+ ## Set the Cloud Role Name and the Cloud Role Instance
166
+
167
+ You might set the Cloud Role Name and the Cloud Role Instance via [OpenTelemetry Resource](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/sdk.md#resource-sdk) attributes.
168
+
169
+
170
+ ```typescript
171
+ const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
172
+ const { Resource } = require("@opentelemetry/resources");
173
+ const { SemanticResourceAttributes } = require("@opentelemetry/semantic-conventions");
174
+
175
+ // ----------------------------------------
176
+ // Setting role name and role instance
177
+ // ----------------------------------------
178
+ const customResource = Resource.EMPTY;
179
+ customResource.attributes[SemanticResourceAttributes.SERVICE_NAME] = "my-helloworld-service";
180
+ customResource.attributes[SemanticResourceAttributes.SERVICE_NAMESPACE] = "my-namespace";
181
+ customResource.attributes[SemanticResourceAttributes.SERVICE_INSTANCE_ID] = "my-instance";
182
+
183
+ const options: AzureMonitorOpenTelemetryOptions = { resource : customResource }
184
+ useAzureMonitor(options);
185
+ ```
186
+
187
+ For information on standard attributes for resources, see [Resource Semantic Conventions](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md).
188
+
189
+
190
+ ## Modify telemetry
191
+
192
+ This section explains how to modify telemetry.
193
+
194
+ ### Add span attributes
195
+
196
+ To add span attributes, use either of the following two ways:
197
+
198
+ * Use options provided by [instrumentation libraries](#instrumentation-libraries).
199
+ * Add a custom span processor.
200
+
201
+ These attributes might include adding a custom property to your telemetry.
202
+
203
+ > *Tip:* The advantage of using options provided by instrumentation libraries, when they're available, is that the entire context is available. As a result, users can select to add or filter more attributes. For example, the enrich option in the HttpClient instrumentation library gives users access to the httpRequestMessage itself. They can select anything from it and store it as an attribute.
204
+
205
+ #### Add a custom property to a Trace
206
+
207
+ Any [attributes](#add-span-attributes) you add to spans are exported as custom properties.
208
+
209
+ Use a custom processor:
210
+
211
+ ```typescript
212
+ const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
213
+ const { trace } = require("@opentelemetry/api");
214
+ const { ReadableSpan, Span, SpanProcessor } = require("@opentelemetry/sdk-trace-base");
57
215
  const { NodeTracerProvider } = require("@opentelemetry/sdk-trace-node");
216
+ const { SemanticAttributes } = require("@opentelemetry/semantic-conventions");
217
+
218
+ useAzureMonitor();
219
+
220
+ class SpanEnrichingProcessor implements SpanProcessor{
221
+ forceFlush(): Promise<void>{
222
+ return Promise.resolve();
223
+ }
224
+ shutdown(): Promise<void>{
225
+ return Promise.resolve();
226
+ }
227
+ onStart(_span: Span): void{}
228
+ onEnd(span: ReadableSpan){
229
+ span.attributes["CustomDimension1"] = "value1";
230
+ span.attributes["CustomDimension2"] = "value2";
231
+ span.attributes[SemanticAttributes.HTTP_CLIENT_IP] = "<IP Address>";
232
+ }
233
+ }
58
234
 
59
- const provider = new NodeTracerProvider();
60
- diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.ALL);
61
- provider.register();
235
+ const tracerProvider = trace.getTracerProvider().getDelegate();
236
+ tracerProvider.addSpanProcessor(new SpanEnrichingProcessor());
62
237
  ```
63
238
 
239
+ ### Filter telemetry
240
+
241
+ You might use the following ways to filter out telemetry before it leaves your application.
242
+
243
+ 1. Exclude the URL option provided by many HTTP instrumentation libraries.
244
+
245
+ The following example shows how to exclude a certain URL from being tracked by using the [HTTP/HTTPS instrumentation library](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http):
246
+
247
+ ```typescript
248
+ const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
249
+ const { IncomingMessage } = require("http");
250
+ const { RequestOptions } = require("https");
251
+ const { HttpInstrumentationConfig }= require("@opentelemetry/instrumentation-http");
252
+
253
+ const httpInstrumentationConfig: HttpInstrumentationConfig = {
254
+ enabled: true,
255
+ ignoreIncomingRequestHook: (request: IncomingMessage) => {
256
+ // Ignore OPTIONS incoming requests
257
+ if (request.method === 'OPTIONS') {
258
+ return true;
259
+ }
260
+ return false;
261
+ },
262
+ ignoreOutgoingRequestHook: (options: RequestOptions) => {
263
+ // Ignore outgoing requests with /test path
264
+ if (options.path === '/test') {
265
+ return true;
266
+ }
267
+ return false;
268
+ }
269
+ };
270
+ const options : AzureMonitorOpenTelemetryOptions = {
271
+ instrumentationOptions: {
272
+ http: httpInstrumentationConfig,
273
+ }
274
+ };
275
+ useAzureMonitor(options);
276
+
277
+ ```
278
+
279
+ 1. Use a custom processor. You can use a custom span processor to exclude certain spans from being exported. To mark spans to not be exported, set `TraceFlag` to `DEFAULT`.
280
+ Use the add [custom property example](#add-a-custom-property-to-a-trace), but replace the following lines of code:
281
+
282
+ ```typescript
283
+ ...
284
+ import { SpanKind, TraceFlags } from "@opentelemetry/api";
285
+
286
+ class SpanEnrichingProcessor implements SpanProcessor{
287
+ ...
288
+
289
+ onEnd(span: ReadableSpan) {
290
+ if(span.kind == SpanKind.INTERNAL){
291
+ span.spanContext().traceFlags = TraceFlags.NONE;
292
+ }
293
+ }
294
+ }
295
+ ```
296
+
297
+ ## Custom telemetry
298
+
299
+ This section explains how to collect custom telemetry from your application.
300
+
301
+ ### Add Custom Metrics
302
+
303
+ You may want to collect metrics beyond what is collected by [instrumentation libraries](#instrumentation-libraries).
304
+
305
+ The OpenTelemetry API offers six metric "instruments" to cover a variety of metric scenarios and you'll need to pick the correct "Aggregation Type" when visualizing metrics in Metrics Explorer. This requirement is true when using the OpenTelemetry Metric API to send metrics and when using an instrumentation library.
306
+
307
+
308
+ The following table shows the recommended aggregation types] for each of the OpenTelemetry Metric Instruments.
309
+
310
+ | OpenTelemetry Instrument | Azure Monitor Aggregation Type |
311
+ |------------------------------------------------------|------------------------------------------------------------|
312
+ | Counter | Sum |
313
+ | Asynchronous Counter | Sum |
314
+ | Histogram | Average, Sum, Count (Max, Min for Python and Node.js only) |
315
+ | Asynchronous Gauge | Average |
316
+ | UpDownCounter (Python and Node.js only) | Sum |
317
+ | Asynchronous UpDownCounter (Python and Node.js only) | Sum |
318
+
319
+ >> *Caution:* Aggregation types beyond what's shown in the table typically aren't meaningful.
320
+
321
+ The [OpenTelemetry Specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument)
322
+ describes the instruments and provides examples of when you might use each one.
323
+
324
+ ```typescript
325
+ const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
326
+ const { metrics } = require("@opentelemetry/api");
327
+
328
+ useAzureMonitor();
329
+ const meter = metrics.getMeter("testMeter");
330
+
331
+ let histogram = meter.createHistogram("histogram");
332
+ let counter = meter.createCounter("counter");
333
+ let gauge = meter.createObservableGauge("gauge");
334
+ gauge.addCallback((observableResult: ObservableResult) => {
335
+ let randomNumber = Math.floor(Math.random() * 100);
336
+ observableResult.observe(randomNumber, {"testKey": "testValue"});
337
+ });
338
+
339
+ histogram.record(1, { "testKey": "testValue" });
340
+ histogram.record(30, { "testKey": "testValue2" });
341
+ histogram.record(100, { "testKey2": "testValue" });
342
+
343
+ counter.add(1, { "testKey": "testValue" });
344
+ counter.add(5, { "testKey2": "testValue" });
345
+ counter.add(3, { "testKey": "testValue2" });
346
+ ```
347
+
348
+
349
+ ### Add Custom Exceptions
350
+
351
+ Select instrumentation libraries automatically support exceptions to Application Insights.
352
+ However, you may want to manually report exceptions beyond what instrumention libraries report.
353
+ For instance, exceptions caught by your code are *not* ordinarily not reported, and you may wish to report them
354
+ and thus draw attention to them in relevant experiences including the failures blade and end-to-end transaction view.
355
+
356
+ ```typescript
357
+ const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
358
+ const { trace } = require("@opentelemetry/api");
359
+
360
+ useAzureMonitor();
361
+ const tracer = trace.getTracer("testMeter");
362
+
363
+ let span = tracer.startSpan("hello");
364
+ try{
365
+ throw new Error("Test Error");
366
+ }
367
+ catch(error){
368
+ span.recordException(error);
369
+ }
370
+ ```
371
+
372
+ ## Troubleshooting
373
+
374
+ ### Self-diagnostics
375
+
376
+ Azure Monitor OpenTelemetry uses the OpenTelemetry API Logger for internal logs. To enable it, use the following code:
377
+
378
+ ```typescript
379
+ const { useAzureMonitor } = require("@azure/monitor-opentelemetry");
380
+ const { DiagLogLevel } = require("@opentelemetry/api");
381
+
382
+ process.env.APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL = "VERBOSE";
383
+ process.env.APPLICATIONINSIGHTS_LOG_DESTINATION = "file";
384
+ process.env.APPLICATIONINSIGHTS_LOGDIR = "C:/applicationinsights/logs";
385
+
386
+ useAzureMonitor();
387
+ ```
388
+
389
+ `APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL` environment varialbe could be used to set desired log level, supporting the following values: `NONE`, `ERROR`, `WARN`, `INFO`, `DEBUG`, `VERBOSE` and `ALL`.
390
+
391
+ Logs could be put into local file using `APPLICATIONINSIGHTS_LOG_DESTINATION` environment variable, supported values are `file` and `file+console`, a file named `applicationinsights.log` will be generated on tmp folder by default, including all logs, `/tmp` for *nix and `USERDIR/AppData/Local/Temp` for Windows. Log directory could be configured using `APPLICATIONINSIGHTS_LOGDIR` environment variable.
392
+
393
+
394
+ ## Examples
395
+
396
+ For complete samples of a few champion scenarios, see the [`samples/`](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/monitor/monitor-opentelemetry/samples-dev/) folder.
397
+
398
+ ## Key concepts
399
+
400
+ For more information on the OpenTelemetry project, please review the [**OpenTelemetry Specifications**](https://github.com/open-telemetry/opentelemetry-specification#opentelemetry-specification).
401
+
402
+
64
403
  ### Plugin Registry
65
404
 
66
405
  To see if a plugin has already been made for a library you are using, please check out the [OpenTelemetry Registry](https://opentelemetry.io/registry/).