@azure/monitor-opentelemetry 1.3.0 → 1.4.0

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
@@ -79,7 +79,7 @@ const options: AzureMonitorOpenTelemetryOptions = {
79
79
  enabled: false,
80
80
  connectionString: "",
81
81
  },
82
- resource: resource
82
+ resource: resource,
83
83
  logRecordProcessors: [],
84
84
  spanProcessors: []
85
85
  };
@@ -95,11 +95,12 @@ useAzureMonitor(options);
95
95
  | instrumentationOptions| Allow configuration of OpenTelemetry Instrumentations. | {"http": { enabled: true },"azureSdk": { enabled: false },"mongoDb": { enabled: false },"mySql": { enabled: false },"postgreSql": { enabled: false },"redis": { enabled: false },"bunyan": { enabled: false }}|
96
96
  | browserSdkLoaderOptions| Allow configuration of Web Instrumentations. | { enabled: false, connectionString: "" } |
97
97
  | resource | Opentelemetry Resource. [More info here](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-resources) ||
98
- | 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. |
99
- | enableLiveMetrics | Enable/Disable Live Metrics. |
100
- | enableStandardMetrics | Enable/Disable Standard Metrics. |
101
- | logRecordProcessors | Array of log record processors to register to the global logger provider. |
102
- | spanProcessors | Array of span processors to register to the global tracer provider. |
98
+ | 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|
99
+ | enableLiveMetrics | Enable/Disable Live Metrics. |false|
100
+ | enableStandardMetrics | Enable/Disable Standard Metrics. |true|
101
+ | logRecordProcessors | Array of log record processors to register to the global logger provider. ||
102
+ | spanProcessors | Array of span processors to register to the global tracer provider. ||
103
+ <!--- TODO: Enable when feature is released | enableTraceBasedSamplingForLogs | Enable log sampling based on trace. |true|-->
103
104
 
104
105
  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.
105
106
 
@@ -226,13 +227,10 @@ Any [attributes](#add-span-attributes) you add to spans are exported as custom p
226
227
  Use a custom processor:
227
228
 
228
229
  ```typescript
229
- import { useAzureMonitor } from "@azure/monitor-opentelemetry";
230
- import { ProxyTracerProvider, trace } from "@opentelemetry/api";
230
+ import { useAzureMonitor, AzureMonitorOpenTelemetryOptions } from "@azure/monitor-opentelemetry";
231
231
  import { ReadableSpan, Span, SpanProcessor } from "@opentelemetry/sdk-trace-base";
232
- import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
233
232
  import { SemanticAttributes } from "@opentelemetry/semantic-conventions";
234
233
 
235
- useAzureMonitor();
236
234
 
237
235
  class SpanEnrichingProcessor implements SpanProcessor{
238
236
  forceFlush(): Promise<void>{
@@ -249,8 +247,12 @@ class SpanEnrichingProcessor implements SpanProcessor{
249
247
  }
250
248
  }
251
249
 
252
- const tracerProvider = (trace.getTracerProvider() as ProxyTracerProvider).getDelegate() as NodeTracerProvider;
253
- tracerProvider.addSpanProcessor(new SpanEnrichingProcessor());
250
+ // Enable Azure Monitor integration.
251
+ const options: AzureMonitorOpenTelemetryOptions = {
252
+ // Add the SpanEnrichingProcessor
253
+ spanProcessors: [new SpanEnrichingProcessor()]
254
+ }
255
+ useAzureMonitor(options);
254
256
  ```
255
257
 
256
258
  ### Filter telemetry
package/dist/index.js CHANGED
@@ -497,6 +497,7 @@ class JsonConfig {
497
497
  this.browserSdkLoaderOptions = jsonConfig.browserSdkLoaderOptions;
498
498
  this.enableLiveMetrics = jsonConfig.enableLiveMetrics;
499
499
  this.enableStandardMetrics = jsonConfig.enableStandardMetrics;
500
+ this.enableTraceBasedSamplingForLogs = jsonConfig.enableTraceBasedSamplingForLogs;
500
501
  }
501
502
  catch (err) {
502
503
  Logger.getInstance().info("Missing or invalid JSON config file: ", err);
@@ -529,6 +530,7 @@ class InternalConfig {
529
530
  this.samplingRatio = 1;
530
531
  this.enableLiveMetrics = false;
531
532
  this.enableStandardMetrics = true;
533
+ this.enableTraceBasedSamplingForLogs = true;
532
534
  this.instrumentationOptions = {
533
535
  http: { enabled: true },
534
536
  azureSdk: { enabled: false },
@@ -550,8 +552,16 @@ class InternalConfig {
550
552
  this.resource = Object.assign(this.resource, options.resource);
551
553
  this.samplingRatio = options.samplingRatio || this.samplingRatio;
552
554
  this.browserSdkLoaderOptions = Object.assign(this.browserSdkLoaderOptions, options.browserSdkLoaderOptions);
553
- this.enableLiveMetrics = options.enableLiveMetrics || this.enableLiveMetrics;
554
- this.enableStandardMetrics = options.enableStandardMetrics || this.enableStandardMetrics;
555
+ this.enableLiveMetrics =
556
+ options.enableLiveMetrics != undefined ? options.enableLiveMetrics : this.enableLiveMetrics;
557
+ this.enableStandardMetrics =
558
+ options.enableStandardMetrics != undefined
559
+ ? options.enableStandardMetrics
560
+ : this.enableStandardMetrics;
561
+ this.enableTraceBasedSamplingForLogs =
562
+ options.enableTraceBasedSamplingForLogs != undefined
563
+ ? options.enableTraceBasedSamplingForLogs
564
+ : this.enableTraceBasedSamplingForLogs;
555
565
  }
556
566
  // JSON configuration will take precedence over other settings
557
567
  this._mergeConfig();
@@ -570,6 +580,10 @@ class InternalConfig {
570
580
  jsonConfig.enableStandardMetrics !== undefined
571
581
  ? jsonConfig.enableStandardMetrics
572
582
  : this.enableStandardMetrics;
583
+ this.enableTraceBasedSamplingForLogs =
584
+ jsonConfig.enableTraceBasedSamplingForLogs !== undefined
585
+ ? jsonConfig.enableTraceBasedSamplingForLogs
586
+ : this.enableTraceBasedSamplingForLogs;
573
587
  this.azureMonitorExporterOptions = Object.assign(this.azureMonitorExporterOptions, jsonConfig.azureMonitorExporterOptions);
574
588
  this.instrumentationOptions = Object.assign(this.instrumentationOptions, jsonConfig.instrumentationOptions);
575
589
  }
@@ -2055,7 +2069,7 @@ const publishOperationSpec = {
2055
2069
  // Licensed under the MIT license.
2056
2070
  // Copyright (c) Microsoft Corporation.
2057
2071
  // Licensed under the MIT license.
2058
- const AZURE_MONITOR_OPENTELEMETRY_VERSION = "1.3.0";
2072
+ const AZURE_MONITOR_OPENTELEMETRY_VERSION = "1.4.0";
2059
2073
  const AZURE_MONITOR_STATSBEAT_FEATURES = "AZURE_MONITOR_STATSBEAT_FEATURES";
2060
2074
  const AZURE_MONITOR_PREFIX = "AZURE_MONITOR_PREFIX";
2061
2075
  const AZURE_MONITOR_AUTO_ATTACH = "AZURE_MONITOR_AUTO_ATTACH";
@@ -2086,6 +2100,7 @@ var StatsbeatFeature;
2086
2100
  StatsbeatFeature[StatsbeatFeature["AAD_HANDLING"] = 2] = "AAD_HANDLING";
2087
2101
  StatsbeatFeature[StatsbeatFeature["BROWSER_SDK_LOADER"] = 4] = "BROWSER_SDK_LOADER";
2088
2102
  StatsbeatFeature[StatsbeatFeature["DISTRO"] = 8] = "DISTRO";
2103
+ StatsbeatFeature[StatsbeatFeature["LIVE_METRICS"] = 16] = "LIVE_METRICS";
2089
2104
  })(StatsbeatFeature || (StatsbeatFeature = {}));
2090
2105
  var StatsbeatInstrumentation;
2091
2106
  (function (StatsbeatInstrumentation) {
@@ -2638,6 +2653,71 @@ class ConnectionStringParser {
2638
2653
  ConnectionStringParser.FIELDS_SEPARATOR = ";";
2639
2654
  ConnectionStringParser.FIELD_KEY_VALUE_SEPARATOR = "=";
2640
2655
 
2656
+ // Copyright (c) Microsoft Corporation.
2657
+ // Licensed under the MIT license.
2658
+ let instance;
2659
+ class StatsbeatConfiguration {
2660
+ constructor() {
2661
+ // Initial Statsbeat options
2662
+ this.currentStatsbeatOptions = {};
2663
+ this.setStatsbeatFeatures = (statsbeatOptions) => {
2664
+ // Merge old statsbeat options with new statsbeat options overriding any common properties
2665
+ this.currentStatsbeatOptions = Object.assign(Object.assign({}, this.currentStatsbeatOptions), statsbeatOptions);
2666
+ let instrumentationBitMap = StatsbeatInstrumentation.NONE;
2667
+ if (statsbeatOptions.azureSdk === true) {
2668
+ instrumentationBitMap |= StatsbeatInstrumentation.AZURE_CORE_TRACING;
2669
+ }
2670
+ if (statsbeatOptions.mongoDb === true) {
2671
+ instrumentationBitMap |= StatsbeatInstrumentation.MONGODB;
2672
+ }
2673
+ if (statsbeatOptions.mySql === true) {
2674
+ instrumentationBitMap |= StatsbeatInstrumentation.MYSQL;
2675
+ }
2676
+ if (statsbeatOptions.postgreSql === true) {
2677
+ instrumentationBitMap |= StatsbeatInstrumentation.POSTGRES;
2678
+ }
2679
+ if (statsbeatOptions.redis === true) {
2680
+ instrumentationBitMap |= StatsbeatInstrumentation.REDIS;
2681
+ }
2682
+ if (statsbeatOptions.bunyan === true) {
2683
+ instrumentationBitMap |= StatsbeatInstrumentation.BUNYAN;
2684
+ }
2685
+ let featureBitMap = StatsbeatFeature.NONE;
2686
+ featureBitMap |= StatsbeatFeature.DISTRO;
2687
+ if (statsbeatOptions.browserSdkLoader === true) {
2688
+ featureBitMap |= StatsbeatFeature.BROWSER_SDK_LOADER;
2689
+ }
2690
+ // Determines if the customer has activated the Live Metrics feature
2691
+ if (statsbeatOptions.liveMetrics === true) {
2692
+ featureBitMap |= StatsbeatFeature.LIVE_METRICS;
2693
+ }
2694
+ try {
2695
+ const currentFeaturesBitMap = Number(process.env[AZURE_MONITOR_STATSBEAT_FEATURES]);
2696
+ if (!isNaN(currentFeaturesBitMap)) {
2697
+ featureBitMap |= currentFeaturesBitMap;
2698
+ }
2699
+ process.env[AZURE_MONITOR_STATSBEAT_FEATURES] = JSON.stringify({
2700
+ instrumentation: instrumentationBitMap,
2701
+ feature: featureBitMap,
2702
+ });
2703
+ }
2704
+ catch (error) {
2705
+ Logger.getInstance().error("Failed call to JSON.stringify.", error);
2706
+ }
2707
+ };
2708
+ }
2709
+ }
2710
+ /**
2711
+ * Singleton Statsbeat instance.
2712
+ * @internal
2713
+ */
2714
+ function getInstance() {
2715
+ if (!instance) {
2716
+ instance = new StatsbeatConfiguration();
2717
+ }
2718
+ return instance;
2719
+ }
2720
+
2641
2721
  // Copyright (c) Microsoft Corporation.
2642
2722
  // Licensed under the MIT license.
2643
2723
  const POST_INTERVAL = 1000;
@@ -2680,6 +2760,7 @@ class LiveMetrics {
2680
2760
  this.lastDependencyRate = { count: 0, time: 0 };
2681
2761
  this.lastFailedDependencyRate = { count: 0, time: 0 };
2682
2762
  this.lastExceptionRate = { count: 0, time: 0 };
2763
+ this.statsbeatOptionsUpdated = false;
2683
2764
  this.config = config;
2684
2765
  let idGenerator = new sdkTraceBase.RandomIdGenerator();
2685
2766
  const streamId = idGenerator.generateTraceId();
@@ -2789,6 +2870,11 @@ class LiveMetrics {
2789
2870
  if (this.meterProvider) {
2790
2871
  return;
2791
2872
  }
2873
+ // Turn on live metrics active collection for statsbeat
2874
+ if (!this.statsbeatOptionsUpdated) {
2875
+ getInstance().setStatsbeatFeatures({ liveMetrics: true });
2876
+ this.statsbeatOptionsUpdated = true;
2877
+ }
2792
2878
  this.lastCpus = os__namespace.cpus();
2793
2879
  this.totalDependencyCount = 0;
2794
2880
  this.totalExceptionCount = 0;
@@ -3434,6 +3520,31 @@ class AzureLogRecordProcessor {
3434
3520
  }
3435
3521
  }
3436
3522
 
3523
+ // Copyright (c) Microsoft Corporation.
3524
+ // Licensed under the MIT license.
3525
+ /**
3526
+ * Azure Monitor BatchLogRecord Processor.
3527
+ * @internal
3528
+ */
3529
+ class AzureBatchLogRecordProcessor extends sdkLogs.BatchLogRecordProcessor {
3530
+ constructor(exporter, options) {
3531
+ super(exporter);
3532
+ this._options = options;
3533
+ }
3534
+ onEmit(logRecord) {
3535
+ // Trace based sampling for logs
3536
+ if (this._options.enableTraceBasedSamplingForLogs) {
3537
+ if (logRecord.spanContext && logRecord.spanContext.spanId) {
3538
+ if (logRecord.spanContext.traceFlags != api.TraceFlags.SAMPLED) {
3539
+ // Do not export log for spans that were sampled out
3540
+ return;
3541
+ }
3542
+ }
3543
+ }
3544
+ super.onEmit(logRecord);
3545
+ }
3546
+ }
3547
+
3437
3548
  // Copyright (c) Microsoft Corporation.
3438
3549
  // Licensed under the MIT license.
3439
3550
  /**
@@ -3449,7 +3560,9 @@ class LogHandler {
3449
3560
  this._config = config;
3450
3561
  this._metricHandler = metricHandler;
3451
3562
  this._azureExporter = new monitorOpentelemetryExporter.AzureMonitorLogExporter(config.azureMonitorExporterOptions);
3452
- this._batchLogRecordProcessor = new sdkLogs.BatchLogRecordProcessor(this._azureExporter);
3563
+ this._azureBatchLogRecordProcessor = new AzureBatchLogRecordProcessor(this._azureExporter, {
3564
+ enableTraceBasedSamplingForLogs: this._config.enableTraceBasedSamplingForLogs,
3565
+ });
3453
3566
  this._azureLogRecordProcessor = new AzureLogRecordProcessor(this._metricHandler);
3454
3567
  this._instrumentations = [];
3455
3568
  this._initializeInstrumentations();
@@ -3458,7 +3571,7 @@ class LogHandler {
3458
3571
  return this._azureLogRecordProcessor;
3459
3572
  }
3460
3573
  getBatchLogRecordProcessor() {
3461
- return this._batchLogRecordProcessor;
3574
+ return this._azureBatchLogRecordProcessor;
3462
3575
  }
3463
3576
  getInstrumentations() {
3464
3577
  return this._instrumentations;
@@ -3880,11 +3993,25 @@ let browserSdkLoader;
3880
3993
  * @param options Azure Monitor OpenTelemetry Options
3881
3994
  */
3882
3995
  function useAzureMonitor(options) {
3996
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
3883
3997
  const config = new InternalConfig(options);
3998
+ const statsbeatOptions = {
3999
+ // Instrumentations
4000
+ azureSdk: (_b = (_a = config.instrumentationOptions) === null || _a === void 0 ? void 0 : _a.azureSdk) === null || _b === void 0 ? void 0 : _b.enabled,
4001
+ mongoDb: (_d = (_c = config.instrumentationOptions) === null || _c === void 0 ? void 0 : _c.mongoDb) === null || _d === void 0 ? void 0 : _d.enabled,
4002
+ mySql: (_f = (_e = config.instrumentationOptions) === null || _e === void 0 ? void 0 : _e.mySql) === null || _f === void 0 ? void 0 : _f.enabled,
4003
+ postgreSql: (_h = (_g = config.instrumentationOptions) === null || _g === void 0 ? void 0 : _g.postgreSql) === null || _h === void 0 ? void 0 : _h.enabled,
4004
+ redis: (_k = (_j = config.instrumentationOptions) === null || _j === void 0 ? void 0 : _j.redis) === null || _k === void 0 ? void 0 : _k.enabled,
4005
+ bunyan: (_m = (_l = config.instrumentationOptions) === null || _l === void 0 ? void 0 : _l.bunyan) === null || _m === void 0 ? void 0 : _m.enabled,
4006
+ // Features
4007
+ browserSdkLoader: config.browserSdkLoaderOptions.enabled,
4008
+ aadHandling: !!((_o = config.azureMonitorExporterOptions) === null || _o === void 0 ? void 0 : _o.credential),
4009
+ diskRetry: !((_p = config.azureMonitorExporterOptions) === null || _p === void 0 ? void 0 : _p.disableOfflineStorage),
4010
+ };
4011
+ getInstance().setStatsbeatFeatures(statsbeatOptions);
3884
4012
  if (config.browserSdkLoaderOptions.enabled) {
3885
4013
  browserSdkLoader = new BrowserSdkLoader(config);
3886
4014
  }
3887
- _setStatsbeatFeatures(config, browserSdkLoader);
3888
4015
  // Remove global providers in OpenTelemetry, these would be overriden if present
3889
4016
  api.metrics.disable();
3890
4017
  api.trace.disable();
@@ -3947,46 +4074,6 @@ function shutdownAzureMonitor() {
3947
4074
  browserSdkLoader === null || browserSdkLoader === void 0 ? void 0 : browserSdkLoader.dispose();
3948
4075
  return sdk === null || sdk === void 0 ? void 0 : sdk.shutdown();
3949
4076
  }
3950
- function _setStatsbeatFeatures(config, browserSdkLoader) {
3951
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
3952
- let instrumentationBitMap = StatsbeatInstrumentation.NONE;
3953
- if ((_b = (_a = config.instrumentationOptions) === null || _a === void 0 ? void 0 : _a.azureSdk) === null || _b === void 0 ? void 0 : _b.enabled) {
3954
- instrumentationBitMap |= StatsbeatInstrumentation.AZURE_CORE_TRACING;
3955
- }
3956
- if ((_d = (_c = config.instrumentationOptions) === null || _c === void 0 ? void 0 : _c.mongoDb) === null || _d === void 0 ? void 0 : _d.enabled) {
3957
- instrumentationBitMap |= StatsbeatInstrumentation.MONGODB;
3958
- }
3959
- if ((_f = (_e = config.instrumentationOptions) === null || _e === void 0 ? void 0 : _e.mySql) === null || _f === void 0 ? void 0 : _f.enabled) {
3960
- instrumentationBitMap |= StatsbeatInstrumentation.MYSQL;
3961
- }
3962
- if ((_h = (_g = config.instrumentationOptions) === null || _g === void 0 ? void 0 : _g.postgreSql) === null || _h === void 0 ? void 0 : _h.enabled) {
3963
- instrumentationBitMap |= StatsbeatInstrumentation.POSTGRES;
3964
- }
3965
- if ((_k = (_j = config.instrumentationOptions) === null || _j === void 0 ? void 0 : _j.redis) === null || _k === void 0 ? void 0 : _k.enabled) {
3966
- instrumentationBitMap |= StatsbeatInstrumentation.REDIS;
3967
- }
3968
- if ((_m = (_l = config.instrumentationOptions) === null || _l === void 0 ? void 0 : _l.bunyan) === null || _m === void 0 ? void 0 : _m.enabled) {
3969
- instrumentationBitMap |= StatsbeatInstrumentation.BUNYAN;
3970
- }
3971
- let featureBitMap = StatsbeatFeature.NONE;
3972
- featureBitMap |= StatsbeatFeature.DISTRO;
3973
- if (browserSdkLoader === null || browserSdkLoader === void 0 ? void 0 : browserSdkLoader.isInitialized()) {
3974
- featureBitMap |= StatsbeatFeature.BROWSER_SDK_LOADER;
3975
- }
3976
- try {
3977
- const currentFeaturesBitMap = Number(process.env[AZURE_MONITOR_STATSBEAT_FEATURES]);
3978
- if (!isNaN(currentFeaturesBitMap)) {
3979
- featureBitMap |= currentFeaturesBitMap;
3980
- }
3981
- process.env[AZURE_MONITOR_STATSBEAT_FEATURES] = JSON.stringify({
3982
- instrumentation: instrumentationBitMap,
3983
- feature: featureBitMap,
3984
- });
3985
- }
3986
- catch (error) {
3987
- Logger.getInstance().error("Failed call to JSON.stringify.", error);
3988
- }
3989
- }
3990
4077
 
3991
4078
  exports.shutdownAzureMonitor = shutdownAzureMonitor;
3992
4079
  exports.useAzureMonitor = useAzureMonitor;
@@ -8,9 +8,10 @@ import { MetricHandler } from "./metrics";
8
8
  import { TraceHandler } from "./traces/handler";
9
9
  import { Logger as InternalLogger } from "./shared/logging";
10
10
  import { LogHandler } from "./logs";
11
- import { AZURE_MONITOR_OPENTELEMETRY_VERSION, AZURE_MONITOR_STATSBEAT_FEATURES, StatsbeatFeature, StatsbeatInstrumentation, } from "./types";
11
+ import { AZURE_MONITOR_OPENTELEMETRY_VERSION, } from "./types";
12
12
  import { BrowserSdkLoader } from "./browserSdkLoader/browserSdkLoader";
13
13
  import { setSdkPrefix } from "./metrics/quickpulse/utils";
14
+ import { getInstance } from "./utils/statsbeat";
14
15
  process.env["AZURE_MONITOR_DISTRO_VERSION"] = AZURE_MONITOR_OPENTELEMETRY_VERSION;
15
16
  let sdk;
16
17
  let browserSdkLoader;
@@ -19,11 +20,25 @@ let browserSdkLoader;
19
20
  * @param options Azure Monitor OpenTelemetry Options
20
21
  */
21
22
  export function useAzureMonitor(options) {
23
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
22
24
  const config = new InternalConfig(options);
25
+ const statsbeatOptions = {
26
+ // Instrumentations
27
+ azureSdk: (_b = (_a = config.instrumentationOptions) === null || _a === void 0 ? void 0 : _a.azureSdk) === null || _b === void 0 ? void 0 : _b.enabled,
28
+ mongoDb: (_d = (_c = config.instrumentationOptions) === null || _c === void 0 ? void 0 : _c.mongoDb) === null || _d === void 0 ? void 0 : _d.enabled,
29
+ mySql: (_f = (_e = config.instrumentationOptions) === null || _e === void 0 ? void 0 : _e.mySql) === null || _f === void 0 ? void 0 : _f.enabled,
30
+ postgreSql: (_h = (_g = config.instrumentationOptions) === null || _g === void 0 ? void 0 : _g.postgreSql) === null || _h === void 0 ? void 0 : _h.enabled,
31
+ redis: (_k = (_j = config.instrumentationOptions) === null || _j === void 0 ? void 0 : _j.redis) === null || _k === void 0 ? void 0 : _k.enabled,
32
+ bunyan: (_m = (_l = config.instrumentationOptions) === null || _l === void 0 ? void 0 : _l.bunyan) === null || _m === void 0 ? void 0 : _m.enabled,
33
+ // Features
34
+ browserSdkLoader: config.browserSdkLoaderOptions.enabled,
35
+ aadHandling: !!((_o = config.azureMonitorExporterOptions) === null || _o === void 0 ? void 0 : _o.credential),
36
+ diskRetry: !((_p = config.azureMonitorExporterOptions) === null || _p === void 0 ? void 0 : _p.disableOfflineStorage),
37
+ };
38
+ getInstance().setStatsbeatFeatures(statsbeatOptions);
23
39
  if (config.browserSdkLoaderOptions.enabled) {
24
40
  browserSdkLoader = new BrowserSdkLoader(config);
25
41
  }
26
- _setStatsbeatFeatures(config, browserSdkLoader);
27
42
  // Remove global providers in OpenTelemetry, these would be overriden if present
28
43
  metrics.disable();
29
44
  trace.disable();
@@ -86,44 +101,4 @@ export function shutdownAzureMonitor() {
86
101
  browserSdkLoader === null || browserSdkLoader === void 0 ? void 0 : browserSdkLoader.dispose();
87
102
  return sdk === null || sdk === void 0 ? void 0 : sdk.shutdown();
88
103
  }
89
- function _setStatsbeatFeatures(config, browserSdkLoader) {
90
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
91
- let instrumentationBitMap = StatsbeatInstrumentation.NONE;
92
- if ((_b = (_a = config.instrumentationOptions) === null || _a === void 0 ? void 0 : _a.azureSdk) === null || _b === void 0 ? void 0 : _b.enabled) {
93
- instrumentationBitMap |= StatsbeatInstrumentation.AZURE_CORE_TRACING;
94
- }
95
- if ((_d = (_c = config.instrumentationOptions) === null || _c === void 0 ? void 0 : _c.mongoDb) === null || _d === void 0 ? void 0 : _d.enabled) {
96
- instrumentationBitMap |= StatsbeatInstrumentation.MONGODB;
97
- }
98
- if ((_f = (_e = config.instrumentationOptions) === null || _e === void 0 ? void 0 : _e.mySql) === null || _f === void 0 ? void 0 : _f.enabled) {
99
- instrumentationBitMap |= StatsbeatInstrumentation.MYSQL;
100
- }
101
- if ((_h = (_g = config.instrumentationOptions) === null || _g === void 0 ? void 0 : _g.postgreSql) === null || _h === void 0 ? void 0 : _h.enabled) {
102
- instrumentationBitMap |= StatsbeatInstrumentation.POSTGRES;
103
- }
104
- if ((_k = (_j = config.instrumentationOptions) === null || _j === void 0 ? void 0 : _j.redis) === null || _k === void 0 ? void 0 : _k.enabled) {
105
- instrumentationBitMap |= StatsbeatInstrumentation.REDIS;
106
- }
107
- if ((_m = (_l = config.instrumentationOptions) === null || _l === void 0 ? void 0 : _l.bunyan) === null || _m === void 0 ? void 0 : _m.enabled) {
108
- instrumentationBitMap |= StatsbeatInstrumentation.BUNYAN;
109
- }
110
- let featureBitMap = StatsbeatFeature.NONE;
111
- featureBitMap |= StatsbeatFeature.DISTRO;
112
- if (browserSdkLoader === null || browserSdkLoader === void 0 ? void 0 : browserSdkLoader.isInitialized()) {
113
- featureBitMap |= StatsbeatFeature.BROWSER_SDK_LOADER;
114
- }
115
- try {
116
- const currentFeaturesBitMap = Number(process.env[AZURE_MONITOR_STATSBEAT_FEATURES]);
117
- if (!isNaN(currentFeaturesBitMap)) {
118
- featureBitMap |= currentFeaturesBitMap;
119
- }
120
- process.env[AZURE_MONITOR_STATSBEAT_FEATURES] = JSON.stringify({
121
- instrumentation: instrumentationBitMap,
122
- feature: featureBitMap,
123
- });
124
- }
125
- catch (error) {
126
- InternalLogger.getInstance().error("Failed call to JSON.stringify.", error);
127
- }
128
- }
129
104
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAuB,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAwB,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,MAAM,IAAI,cAAc,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AAO,EAAE,CAAC;QAClD,qBAAqB,IAAI,wBAAwB,CAAC,KAAK,CAAC;IAC1D,CAAC;IACD,IAAI,MAAA,MAAA,MAAM,CAAC,sBAAsB,0CAAE,MAAM,0CAAE,OAAO,EAAE,CAAC;QACnD,qBAAqB,IAAI,wBAAwB,CAAC,MAAM,CAAC;IAC3D,CAAC;IAED,IAAI,aAAa,GAAG,gBAAgB,CAAC,IAAI,CAAC;IAC1C,aAAa,IAAI,gBAAgB,CAAC,MAAM,CAAC;IAEzC,IAAI,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,aAAa,EAAE,EAAE,CAAC;QACtC,aAAa,IAAI,gBAAgB,CAAC,kBAAkB,CAAC;IACvD,CAAC;IAED,IAAI,CAAC;QACH,MAAM,qBAAqB,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC,CAAC;QACpF,IAAI,CAAC,KAAK,CAAC,qBAAqB,CAAC,EAAE,CAAC;YAClC,aAAa,IAAI,qBAAqB,CAAC;QACzC,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC;YAC7D,eAAe,EAAE,qBAAqB;YACtC,OAAO,EAAE,aAAa;SACvB,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,cAAc,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ProxyTracerProvider, metrics, trace } from \"@opentelemetry/api\";\nimport { logs } from \"@opentelemetry/api-logs\";\nimport { NodeSDK, NodeSDKConfiguration } from \"@opentelemetry/sdk-node\";\nimport { InternalConfig } from \"./shared/config\";\nimport { MetricHandler } from \"./metrics\";\nimport { TraceHandler } from \"./traces/handler\";\nimport { Logger as InternalLogger } from \"./shared/logging\";\nimport { LogHandler } from \"./logs\";\nimport {\n AZURE_MONITOR_OPENTELEMETRY_VERSION,\n AZURE_MONITOR_STATSBEAT_FEATURES,\n AzureMonitorOpenTelemetryOptions,\n InstrumentationOptions,\n BrowserSdkLoaderOptions,\n StatsbeatFeature,\n StatsbeatInstrumentation,\n} from \"./types\";\nimport { BrowserSdkLoader } from \"./browserSdkLoader/browserSdkLoader\";\nimport { setSdkPrefix } from \"./metrics/quickpulse/utils\";\nimport { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { LogRecordProcessor, LoggerProvider } from \"@opentelemetry/sdk-logs\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\n\nexport { AzureMonitorOpenTelemetryOptions, InstrumentationOptions, BrowserSdkLoaderOptions };\n\nprocess.env[\"AZURE_MONITOR_DISTRO_VERSION\"] = AZURE_MONITOR_OPENTELEMETRY_VERSION;\n\nlet sdk: NodeSDK;\nlet browserSdkLoader: BrowserSdkLoader | undefined;\n\n/**\n * Initialize Azure Monitor Distro\n * @param options Azure Monitor OpenTelemetry Options\n */\nexport function useAzureMonitor(options?: AzureMonitorOpenTelemetryOptions) {\n const config = new InternalConfig(options);\n\n if (config.browserSdkLoaderOptions.enabled) {\n browserSdkLoader = new BrowserSdkLoader(config);\n }\n _setStatsbeatFeatures(config, browserSdkLoader);\n // Remove global providers in OpenTelemetry, these would be overriden if present\n metrics.disable();\n trace.disable();\n logs.disable();\n\n // Create internal handlers\n const metricHandler = new MetricHandler(config);\n const traceHandler = new TraceHandler(config, metricHandler);\n const logHandler = new LogHandler(config, metricHandler);\n\n const instrumentations = traceHandler\n .getInstrumentations()\n .concat(logHandler.getInstrumentations());\n\n // Initialize OpenTelemetry SDK\n const sdkConfig: Partial<NodeSDKConfiguration> = {\n autoDetectResources: true,\n metricReader: metricHandler.getMetricReader(),\n views: metricHandler.getViews(),\n instrumentations: instrumentations,\n logRecordProcessor: logHandler.getAzureLogRecordProcessor(),\n resource: config.resource,\n sampler: traceHandler.getSampler(),\n spanProcessors: [traceHandler.getAzureMonitorSpanProcessor()],\n };\n sdk = new NodeSDK(sdkConfig);\n setSdkPrefix();\n sdk.start();\n\n // TODO: Send processors as NodeSDK config once arrays are supported\n // https://github.com/open-telemetry/opentelemetry-js/issues/4451\n\n // Add extra SpanProcessors, MetricReaders and LogRecordProcessors\n let spanProcessors: SpanProcessor[] = options?.spanProcessors || [];\n // Add batch processor as the last one\n spanProcessors.push(traceHandler.getBatchSpanProcessor());\n\n // Add extra SpanProcessors, MetricReaders and LogRecordProcessors\n let logRecordProcessors: LogRecordProcessor[] = options?.logRecordProcessors || [];\n // Add batch processor as the last one\n logRecordProcessors.push(logHandler.getBatchLogRecordProcessor());\n\n try {\n const tracerProvider = (\n trace.getTracerProvider() as ProxyTracerProvider\n ).getDelegate() as NodeTracerProvider;\n spanProcessors.forEach((spanProcessor) => {\n tracerProvider.addSpanProcessor(spanProcessor);\n });\n } catch (error) {\n InternalLogger.getInstance().error(\"Failed to add SpanProcessors to TracerProvider.\", error);\n }\n try {\n const logProvider = logs.getLoggerProvider() as LoggerProvider;\n logRecordProcessors.forEach((logRecordProcessor) => {\n logProvider.addLogRecordProcessor(logRecordProcessor);\n });\n } catch (error) {\n InternalLogger.getInstance().error(\n \"Failed to add LogRecordProcessors to LoggerProvider.\",\n error,\n );\n }\n}\n\n/**\n * Shutdown Azure Monitor Open Telemetry Distro\n * @see https://github.com/open-telemetry/opentelemetry-js/blob/0229434cb5a3179f63c021105f36270ae7897929/experimental/packages/opentelemetry-sdk-node/src/sdk.ts#L398\n */\nexport function shutdownAzureMonitor(): Promise<void> {\n browserSdkLoader?.dispose();\n return sdk?.shutdown();\n}\n\nfunction _setStatsbeatFeatures(config: InternalConfig, browserSdkLoader?: BrowserSdkLoader) {\n let instrumentationBitMap = StatsbeatInstrumentation.NONE;\n if (config.instrumentationOptions?.azureSdk?.enabled) {\n instrumentationBitMap |= StatsbeatInstrumentation.AZURE_CORE_TRACING;\n }\n if (config.instrumentationOptions?.mongoDb?.enabled) {\n instrumentationBitMap |= StatsbeatInstrumentation.MONGODB;\n }\n if (config.instrumentationOptions?.mySql?.enabled) {\n instrumentationBitMap |= StatsbeatInstrumentation.MYSQL;\n }\n if (config.instrumentationOptions?.postgreSql?.enabled) {\n instrumentationBitMap |= StatsbeatInstrumentation.POSTGRES;\n }\n if (config.instrumentationOptions?.redis?.enabled) {\n instrumentationBitMap |= StatsbeatInstrumentation.REDIS;\n }\n if (config.instrumentationOptions?.bunyan?.enabled) {\n instrumentationBitMap |= StatsbeatInstrumentation.BUNYAN;\n }\n\n let featureBitMap = StatsbeatFeature.NONE;\n featureBitMap |= StatsbeatFeature.DISTRO;\n\n if (browserSdkLoader?.isInitialized()) {\n featureBitMap |= StatsbeatFeature.BROWSER_SDK_LOADER;\n }\n\n try {\n const currentFeaturesBitMap = Number(process.env[AZURE_MONITOR_STATSBEAT_FEATURES]);\n if (!isNaN(currentFeaturesBitMap)) {\n featureBitMap |= currentFeaturesBitMap;\n }\n process.env[AZURE_MONITOR_STATSBEAT_FEATURES] = JSON.stringify({\n instrumentation: instrumentationBitMap,\n feature: featureBitMap,\n });\n } catch (error) {\n InternalLogger.getInstance().error(\"Failed call to JSON.stringify.\", error);\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAuB,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAwB,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,MAAM,IAAI,cAA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AAE,CAAC;AACzB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { ProxyTracerProvider, metrics, trace } from \"@opentelemetry/api\";\nimport { logs } from \"@opentelemetry/api-logs\";\nimport { NodeSDK, NodeSDKConfiguration } from \"@opentelemetry/sdk-node\";\nimport { InternalConfig } from \"./shared/config\";\nimport { MetricHandler } from \"./metrics\";\nimport { TraceHandler } from \"./traces/handler\";\nimport { Logger as InternalLogger } from \"./shared/logging\";\nimport { LogHandler } from \"./logs\";\nimport {\n AZURE_MONITOR_OPENTELEMETRY_VERSION,\n AzureMonitorOpenTelemetryOptions,\n InstrumentationOptions,\n BrowserSdkLoaderOptions,\n StatsbeatOptions,\n} from \"./types\";\nimport { BrowserSdkLoader } from \"./browserSdkLoader/browserSdkLoader\";\nimport { setSdkPrefix } from \"./metrics/quickpulse/utils\";\nimport { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { LogRecordProcessor, LoggerProvider } from \"@opentelemetry/sdk-logs\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport { getInstance } from \"./utils/statsbeat\";\n\nexport { AzureMonitorOpenTelemetryOptions, InstrumentationOptions, BrowserSdkLoaderOptions };\n\nprocess.env[\"AZURE_MONITOR_DISTRO_VERSION\"] = AZURE_MONITOR_OPENTELEMETRY_VERSION;\n\nlet sdk: NodeSDK;\nlet browserSdkLoader: BrowserSdkLoader | undefined;\n\n/**\n * Initialize Azure Monitor Distro\n * @param options Azure Monitor OpenTelemetry Options\n */\nexport function useAzureMonitor(options?: AzureMonitorOpenTelemetryOptions) {\n const config = new InternalConfig(options);\n const statsbeatOptions: StatsbeatOptions = {\n // Instrumentations\n azureSdk: config.instrumentationOptions?.azureSdk?.enabled,\n mongoDb: config.instrumentationOptions?.mongoDb?.enabled,\n mySql: config.instrumentationOptions?.mySql?.enabled,\n postgreSql: config.instrumentationOptions?.postgreSql?.enabled,\n redis: config.instrumentationOptions?.redis?.enabled,\n bunyan: config.instrumentationOptions?.bunyan?.enabled,\n // Features\n browserSdkLoader: config.browserSdkLoaderOptions.enabled,\n aadHandling: !!config.azureMonitorExporterOptions?.credential,\n diskRetry: !config.azureMonitorExporterOptions?.disableOfflineStorage,\n };\n getInstance().setStatsbeatFeatures(statsbeatOptions);\n\n if (config.browserSdkLoaderOptions.enabled) {\n browserSdkLoader = new BrowserSdkLoader(config);\n }\n // Remove global providers in OpenTelemetry, these would be overriden if present\n metrics.disable();\n trace.disable();\n logs.disable();\n\n // Create internal handlers\n const metricHandler = new MetricHandler(config);\n const traceHandler = new TraceHandler(config, metricHandler);\n const logHandler = new LogHandler(config, metricHandler);\n\n const instrumentations = traceHandler\n .getInstrumentations()\n .concat(logHandler.getInstrumentations());\n\n // Initialize OpenTelemetry SDK\n const sdkConfig: Partial<NodeSDKConfiguration> = {\n autoDetectResources: true,\n metricReader: metricHandler.getMetricReader(),\n views: metricHandler.getViews(),\n instrumentations: instrumentations,\n logRecordProcessor: logHandler.getAzureLogRecordProcessor(),\n resource: config.resource,\n sampler: traceHandler.getSampler(),\n spanProcessors: [traceHandler.getAzureMonitorSpanProcessor()],\n };\n sdk = new NodeSDK(sdkConfig);\n setSdkPrefix();\n sdk.start();\n\n // TODO: Send processors as NodeSDK config once arrays are supported\n // https://github.com/open-telemetry/opentelemetry-js/issues/4451\n\n // Add extra SpanProcessors, MetricReaders and LogRecordProcessors\n let spanProcessors: SpanProcessor[] = options?.spanProcessors || [];\n // Add batch processor as the last one\n spanProcessors.push(traceHandler.getBatchSpanProcessor());\n\n // Add extra SpanProcessors, MetricReaders and LogRecordProcessors\n let logRecordProcessors: LogRecordProcessor[] = options?.logRecordProcessors || [];\n // Add batch processor as the last one\n logRecordProcessors.push(logHandler.getBatchLogRecordProcessor());\n\n try {\n const tracerProvider = (\n trace.getTracerProvider() as ProxyTracerProvider\n ).getDelegate() as NodeTracerProvider;\n spanProcessors.forEach((spanProcessor) => {\n tracerProvider.addSpanProcessor(spanProcessor);\n });\n } catch (error) {\n InternalLogger.getInstance().error(\"Failed to add SpanProcessors to TracerProvider.\", error);\n }\n try {\n const logProvider = logs.getLoggerProvider() as LoggerProvider;\n logRecordProcessors.forEach((logRecordProcessor) => {\n logProvider.addLogRecordProcessor(logRecordProcessor);\n });\n } catch (error) {\n InternalLogger.getInstance().error(\n \"Failed to add LogRecordProcessors to LoggerProvider.\",\n error,\n );\n }\n}\n\n/**\n * Shutdown Azure Monitor Open Telemetry Distro\n * @see https://github.com/open-telemetry/opentelemetry-js/blob/0229434cb5a3179f63c021105f36270ae7897929/experimental/packages/opentelemetry-sdk-node/src/sdk.ts#L398\n */\nexport function shutdownAzureMonitor(): Promise<void> {\n browserSdkLoader?.dispose();\n return sdk?.shutdown();\n}\n"]}
@@ -0,0 +1,27 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { TraceFlags } from "@opentelemetry/api";
4
+ import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";
5
+ /**
6
+ * Azure Monitor BatchLogRecord Processor.
7
+ * @internal
8
+ */
9
+ export class AzureBatchLogRecordProcessor extends BatchLogRecordProcessor {
10
+ constructor(exporter, options) {
11
+ super(exporter);
12
+ this._options = options;
13
+ }
14
+ onEmit(logRecord) {
15
+ // Trace based sampling for logs
16
+ if (this._options.enableTraceBasedSamplingForLogs) {
17
+ if (logRecord.spanContext && logRecord.spanContext.spanId) {
18
+ if (logRecord.spanContext.traceFlags != TraceFlags.SAMPLED) {
19
+ // Do not export log for spans that were sampled out
20
+ return;
21
+ }
22
+ }
23
+ }
24
+ super.onEmit(logRecord);
25
+ }
26
+ }
27
+ //# sourceMappingURL=batchLogRecordProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batchLogRecordProcessor.js","sourceRoot":"","sources":["../../../src/logs/batchLogRecordProcessor.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAa,uBAAuB,EAAqB,MAAM,yBAAyB,CAAC;AAEhG;;;GAGG;AACH,MAAM,OAAO,4BAA6B,SAAQ,uBAAuB;IAGvE,YACE,QAA2B,EAC3B,OAAiE;QAEjE,KAAK,CAAC,QAAQ,CAAC,CAAC;QAChB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAEM,MAAM,CAAC,SAAoB;QAChC,gCAAgC;QAChC,IAAI,IAAI,CAAC,QAAQ,CAAC,+BAA+B,EAAE,CAAC;YAClD,IAAI,SAAS,CAAC,WAAW,IAAI,SAAS,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;gBAC1D,IAAI,SAAS,CAAC,WAAW,CAAC,UAAU,IAAI,UAAU,CAAC,OAAO,EAAE,CAAC;oBAC3D,oDAAoD;oBACpD,OAAO;gBACT,CAAC;YACH,CAAC;QACH,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC1B,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { TraceFlags } from \"@opentelemetry/api\";\nimport { LogRecord, BatchLogRecordProcessor, LogRecordExporter } from \"@opentelemetry/sdk-logs\";\n\n/**\n * Azure Monitor BatchLogRecord Processor.\n * @internal\n */\nexport class AzureBatchLogRecordProcessor extends BatchLogRecordProcessor {\n private readonly _options: { enableTraceBasedSamplingForLogs: boolean | undefined };\n\n constructor(\n exporter: LogRecordExporter,\n options: { enableTraceBasedSamplingForLogs: boolean | undefined },\n ) {\n super(exporter);\n this._options = options;\n }\n\n public onEmit(logRecord: LogRecord): void {\n // Trace based sampling for logs\n if (this._options.enableTraceBasedSamplingForLogs) {\n if (logRecord.spanContext && logRecord.spanContext.spanId) {\n if (logRecord.spanContext.traceFlags != TraceFlags.SAMPLED) {\n // Do not export log for spans that were sampled out\n return;\n }\n }\n }\n super.onEmit(logRecord);\n }\n}\n"]}
@@ -2,8 +2,8 @@
2
2
  // Licensed under the MIT license.
3
3
  import { AzureMonitorLogExporter } from "@azure/monitor-opentelemetry-exporter";
4
4
  import { BunyanInstrumentation } from "@opentelemetry/instrumentation-bunyan";
5
- import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";
6
5
  import { AzureLogRecordProcessor } from "./logRecordProcessor";
6
+ import { AzureBatchLogRecordProcessor } from "./batchLogRecordProcessor";
7
7
  /**
8
8
  * Azure Monitor OpenTelemetry Log Handler
9
9
  */
@@ -17,7 +17,9 @@ export class LogHandler {
17
17
  this._config = config;
18
18
  this._metricHandler = metricHandler;
19
19
  this._azureExporter = new AzureMonitorLogExporter(config.azureMonitorExporterOptions);
20
- this._batchLogRecordProcessor = new BatchLogRecordProcessor(this._azureExporter);
20
+ this._azureBatchLogRecordProcessor = new AzureBatchLogRecordProcessor(this._azureExporter, {
21
+ enableTraceBasedSamplingForLogs: this._config.enableTraceBasedSamplingForLogs,
22
+ });
21
23
  this._azureLogRecordProcessor = new AzureLogRecordProcessor(this._metricHandler);
22
24
  this._instrumentations = [];
23
25
  this._initializeInstrumentations();
@@ -26,7 +28,7 @@ export class LogHandler {
26
28
  return this._azureLogRecordProcessor;
27
29
  }
28
30
  getBatchLogRecordProcessor() {
29
- return this._batchLogRecordProcessor;
31
+ return this._azureBatchLogRecordProcessor;
30
32
  }
31
33
  getInstrumentations() {
32
34
  return this._instrumentations;
@@ -1 +1 @@
1
- {"version":3,"file":"handler.js","sourceRoot":"","sources":["../../../src/logs/handler.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAEhF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAGlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAE/D;;GAEG;AACH,MAAM,OAAO,UAAU;IAQrB;;;;OAIG;IACH,YAAY,MAAsB,EAAE,aAA4B;QAC9D,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;QACpC,IAAI,CAAC,cAAc,GAAG,IAAI,uBAAuB,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC;QACtF,IAAI,CAAC,wBAAwB,GAAG,IAAI,uBAAuB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACjF,IAAI,CAAC,wBAAwB,GAAG,IAAI,uBAAuB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACjF,IAAI,CAAC,iBAAiB,GAAG,EAAE,CAAC;QAC5B,IAAI,CAAC,2BAA2B,EAAE,CAAC;IACrC,CAAC;IAEM,0BAA0B;QAC/B,OAAO,IAAI,CAAC,wBAAwB,CAAC;IACvC,CAAC;IAEM,0BAA0B;QAC/B,OAAO,IAAI,CAAC,wBAAwB,CAAC;IACvC,CAAC;IAEM,mBAAmB;QACxB,OAAO,IAAI,CAAC,iBAAiB,CAAC;IAChC,CAAC;IAED;;OAEG;IACK,2BAA2B;;QACjC,IAAI,MAAA,IAAI,CAAC,OAAO,CAAC,sBAAsB,CAAC,MAAM,0CAAE,OAAO,EAAE,CAAC;YACxD,IAAI,CAAC,iBAAiB,CAAC,IAAI,CACzB,IAAI,qBAAqB,CAAC,IAAI,CAAC,OAAO,CAAC,sBAAsB,CAAC,MAAM,CAAC,CACtE,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureMonitorLogExporter } from \"@azure/monitor-opentelemetry-exporter\";\nimport { Instrumentation } from \"@opentelemetry/instrumentation\";\nimport { BunyanInstrumentation } from \"@opentelemetry/instrumentation-bunyan\";\nimport { BatchLogRecordProcessor } from \"@opentelemetry/sdk-logs\";\nimport { InternalConfig } from \"../shared/config\";\nimport { MetricHandler } from \"../metrics/handler\";\nimport { AzureLogRecordProcessor } from \"./logRecordProcessor\";\n\n/**\n * Azure Monitor OpenTelemetry Log Handler\n */\nexport class LogHandler {\n private _azureExporter: AzureMonitorLogExporter;\n private _azureLogRecordProcessor: AzureLogRecordProcessor;\n private _batchLogRecordProcessor: BatchLogRecordProcessor;\n private _metricHandler: MetricHandler;\n private _config: InternalConfig;\n private _instrumentations: Instrumentation[];\n\n /**\n * Initializes a new instance of the TraceHandler class.\n * @param _config - Distro configuration.\n * @param _metricHandler - MetricHandler.\n */\n constructor(config: InternalConfig, metricHandler: MetricHandler) {\n this._config = config;\n this._metricHandler = metricHandler;\n this._azureExporter = new AzureMonitorLogExporter(config.azureMonitorExporterOptions);\n this._batchLogRecordProcessor = new BatchLogRecordProcessor(this._azureExporter);\n this._azureLogRecordProcessor = new AzureLogRecordProcessor(this._metricHandler);\n this._instrumentations = [];\n this._initializeInstrumentations();\n }\n\n public getAzureLogRecordProcessor(): AzureLogRecordProcessor {\n return this._azureLogRecordProcessor;\n }\n\n public getBatchLogRecordProcessor(): BatchLogRecordProcessor {\n return this._batchLogRecordProcessor;\n }\n\n public getInstrumentations(): Instrumentation[] {\n return this._instrumentations;\n }\n\n /**\n * Start auto collection of telemetry\n */\n private _initializeInstrumentations() {\n if (this._config.instrumentationOptions.bunyan?.enabled) {\n this._instrumentations.push(\n new BunyanInstrumentation(this._config.instrumentationOptions.bunyan),\n );\n }\n }\n}\n"]}
1
+ {"version":3,"file":"handler.js","sourceRoot":"","sources":["../../../src/logs/handler.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAEhF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAI9E,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AAEzE;;GAEG;AACH,MAAM,OAAO,UAAU;IAQrB;;;;OAIG;IACH,YAAY,MAAsB,EAAE,aAA4B;QAC9D,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;QACpC,IAAI,CAAC,cAAc,GAAG,IAAI,uBAAuB,CAAC,MAAM,CAAC,2BAA2B,CAAC,CAAC;QACtF,IAAI,CAAC,6BAA6B,GAAG,IAAI,4BAA4B,CAAC,IAAI,CAAC,cAAc,EAAE;YACzF,+BAA+B,EAAE,IAAI,CAAC,OAAO,CAAC,+BAA+B;SAC9E,CAAC,CAAC;QACH,IAAI,CAAC,wBAAwB,GAAG,IAAI,uBAAuB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACjF,IAAI,CAAC,iBAAiB,GAAG,EAAE,CAAC;QAC5B,IAAI,CAAC,2BAA2B,EAAE,CAAC;IACrC,CAAC;IAEM,0BAA0B;QAC/B,OAAO,IAAI,CAAC,wBAAwB,CAAC;IACvC,CAAC;IAEM,0BAA0B;QAC/B,OAAO,IAAI,CAAC,6BAA6B,CAAC;IAC5C,CAAC;IAEM,mBAAmB;QACxB,OAAO,IAAI,CAAC,iBAAiB,CAAC;IAChC,CAAC;IAED;;OAEG;IACK,2BAA2B;;QACjC,IAAI,MAAA,IAAI,CAAC,OAAO,CAAC,sBAAsB,CAAC,MAAM,0CAAE,OAAO,EAAE,CAAC;YACxD,IAAI,CAAC,iBAAiB,CAAC,IAAI,CACzB,IAAI,qBAAqB,CAAC,IAAI,CAAC,OAAO,CAAC,sBAAsB,CAAC,MAAM,CAAC,CACtE,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureMonitorLogExporter } from \"@azure/monitor-opentelemetry-exporter\";\nimport { Instrumentation } from \"@opentelemetry/instrumentation\";\nimport { BunyanInstrumentation } from \"@opentelemetry/instrumentation-bunyan\";\nimport { BatchLogRecordProcessor } from \"@opentelemetry/sdk-logs\";\nimport { InternalConfig } from \"../shared/config\";\nimport { MetricHandler } from \"../metrics/handler\";\nimport { AzureLogRecordProcessor } from \"./logRecordProcessor\";\nimport { AzureBatchLogRecordProcessor } from \"./batchLogRecordProcessor\";\n\n/**\n * Azure Monitor OpenTelemetry Log Handler\n */\nexport class LogHandler {\n private _azureExporter: AzureMonitorLogExporter;\n private _azureLogRecordProcessor: AzureLogRecordProcessor;\n private _azureBatchLogRecordProcessor: AzureBatchLogRecordProcessor;\n private _metricHandler: MetricHandler;\n private _config: InternalConfig;\n private _instrumentations: Instrumentation[];\n\n /**\n * Initializes a new instance of the TraceHandler class.\n * @param _config - Distro configuration.\n * @param _metricHandler - MetricHandler.\n */\n constructor(config: InternalConfig, metricHandler: MetricHandler) {\n this._config = config;\n this._metricHandler = metricHandler;\n this._azureExporter = new AzureMonitorLogExporter(config.azureMonitorExporterOptions);\n this._azureBatchLogRecordProcessor = new AzureBatchLogRecordProcessor(this._azureExporter, {\n enableTraceBasedSamplingForLogs: this._config.enableTraceBasedSamplingForLogs,\n });\n this._azureLogRecordProcessor = new AzureLogRecordProcessor(this._metricHandler);\n this._instrumentations = [];\n this._initializeInstrumentations();\n }\n\n public getAzureLogRecordProcessor(): AzureLogRecordProcessor {\n return this._azureLogRecordProcessor;\n }\n\n public getBatchLogRecordProcessor(): BatchLogRecordProcessor {\n return this._azureBatchLogRecordProcessor;\n }\n\n public getInstrumentations(): Instrumentation[] {\n return this._instrumentations;\n }\n\n /**\n * Start auto collection of telemetry\n */\n private _initializeInstrumentations() {\n if (this._config.instrumentationOptions.bunyan?.enabled) {\n this._instrumentations.push(\n new BunyanInstrumentation(this._config.instrumentationOptions.bunyan),\n );\n }\n }\n}\n"]}
@@ -12,6 +12,7 @@ import { ConnectionStringParser } from "../../utils/connectionStringParser";
12
12
  import { DEFAULT_LIVEMETRICS_ENDPOINT } from "../../types";
13
13
  import { QuickPulseOpenTelemetryMetricNames } from "./types";
14
14
  import { hrTimeToMilliseconds, suppressTracing } from "@opentelemetry/core";
15
+ import { getInstance } from "../../utils/statsbeat";
15
16
  const POST_INTERVAL = 1000;
16
17
  const MAX_POST_WAIT_TIME = 20000;
17
18
  const PING_INTERVAL = 5000;
@@ -52,6 +53,7 @@ export class LiveMetrics {
52
53
  this.lastDependencyRate = { count: 0, time: 0 };
53
54
  this.lastFailedDependencyRate = { count: 0, time: 0 };
54
55
  this.lastExceptionRate = { count: 0, time: 0 };
56
+ this.statsbeatOptionsUpdated = false;
55
57
  this.config = config;
56
58
  let idGenerator = new RandomIdGenerator();
57
59
  const streamId = idGenerator.generateTraceId();
@@ -161,6 +163,11 @@ export class LiveMetrics {
161
163
  if (this.meterProvider) {
162
164
  return;
163
165
  }
166
+ // Turn on live metrics active collection for statsbeat
167
+ if (!this.statsbeatOptionsUpdated) {
168
+ getInstance().setStatsbeatFeatures({ liveMetrics: true });
169
+ this.statsbeatOptionsUpdated = true;
170
+ }
164
171
  this.lastCpus = os.cpus();
165
172
  this.totalDependencyCount = 0;
166
173
  this.totalExceptionCount = 0;
@@ -1 +1 @@
1
- {"version":3,"file":"liveMetrics.js","sourceRoot":"","sources":["../../../../src/metrics/quickpulse/liveMetrics.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EACL,aAAa,EAEb,6BAA6B,GAE9B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAIL,QAAQ,EACR,cAAc,EACd,SAAS,EACT,OAAO,GACR,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAA4B,MAAM,+BAA+B,CAAC;AAE5F,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAYhD,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,cAAc,EACd,aAAa,EACb,eAAe,EACf,mBAAmB,GACpB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,wBAAwB,EAAE,MAAM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ACD,MAAM,aAAa,GAAG,SAAS,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,GAAG,QAAQ,CAAC;QAC9E,OAAO;YACL,aAAa,EAAE,aAAa;YAC5B,SAAS,EAAE,SAAS;YACpB,SAAS,EAAE,SAAS;SACrB,CAAC;IACJ,CAAC;IAEO,gBAAgB,CAAC,gBAAkC;QACzD,6GAA6G;QAC7G,+CAA+C;QAC/C,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC;QACvB,IAAI,IAAI,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;YACjF,MAAM,SAAS,GAAG,IAAI,CAAC,mBAAmB,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;YAEhE,MAAM,KAAK,GACT,SAAS,CAAC,aAAa,GAAG,CAAC;gBACzB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,aAAa,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC,aAAa,CAAC,GAAG,GAAG;gBACnF,CAAC,CAAC,CAAC,CAAC;YACR,gBAAgB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAClC,CAAC;QACD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport * as os from \"os\";\nimport {\n MeterProvider,\n MeterProviderOptions,\n PeriodicExportingMetricReader,\n PeriodicExportingMetricReaderOptions,\n} from \"@opentelemetry/sdk-metrics\";\nimport { InternalConfig } from \"../../shared/config\";\nimport {\n Meter,\n ObservableGauge,\n ObservableResult,\n SpanKind,\n SpanStatusCode,\n ValueType,\n context,\n} from \"@opentelemetry/api\";\nimport { RandomIdGenerator, ReadableSpan, TimedEvent } from \"@opentelemetry/sdk-trace-base\";\nimport { LogRecord } from \"@opentelemetry/sdk-logs\";\nimport { isExceptionTelemetry } from \"../utils\";\nimport {\n DocumentIngress,\n Exception,\n MonitoringDataPoint,\n IsSubscribedOptionalParams,\n IsSubscribedResponse,\n PublishResponse,\n RemoteDependency,\n Request,\n Trace,\n} from \"../../generated\";\nimport {\n getCloudRole,\n getCloudRoleInstance,\n getLogDocument,\n getSdkVersion,\n getSpanDocument,\n getTransmissionTime,\n} from \"./utils\";\nimport { QuickpulseMetricExporter } from \"./export/exporter\";\nimport { QuickpulseSender } from \"./export/sender\";\nimport { ConnectionStringParser } from \"../../utils/connectionStringParser\";\nimport { DEFAULT_LIVEMETRICS_ENDPOINT } from \"../../types\";\nimport { QuickPulseOpenTelemetryMetricNames, QuickpulseExporterOptions } from \"./types\";\nimport { hrTimeToMilliseconds, suppressTracing } from \"@opentelemetry/core\";\n\nconst POST_INTERVAL = 1000;\nconst MAX_POST_WAIT_TIME = 20000;\nconst PING_INTERVAL = 5000;\nconst MAX_PING_WAIT_TIME = 60000;\nconst FALLBACK_INTERVAL = 60000;\n\n/**\n * Azure Monitor Live Metrics\n * @internal\n */\nexport class LiveMetrics {\n private config: InternalConfig;\n private meterProvider: MeterProvider | undefined;\n private metricReader: PeriodicExportingMetricReader | undefined;\n private meter: Meter | undefined;\n private requestDurationGauge: ObservableGauge | undefined;\n private dependencyDurationGauge: ObservableGauge | undefined;\n private requestRateGauge: ObservableGauge | undefined;\n private requestFailedRateGauge: ObservableGauge | undefined;\n private dependencyRateGauge: ObservableGauge | undefined;\n private dependencyFailedRateGauge: ObservableGauge | undefined;\n private memoryCommitedGauge: ObservableGauge | undefined;\n private processorTimeGauge: ObservableGauge | undefined;\n private exceptionsRateGauge: ObservableGauge | undefined;\n\n private documents: DocumentIngress[] = [];\n private pingInterval: number;\n private postInterval: number;\n private quickpulseExporter: QuickpulseMetricExporter;\n private pingSender: QuickpulseSender;\n private isCollectingData: boolean;\n private lastSuccessTime: number = Date.now();\n private handle: NodeJS.Timer;\n // Monitoring data point with common properties\n private baseMonitoringDataPoint: MonitoringDataPoint;\n private totalRequestCount = 0;\n private totalFailedRequestCount = 0;\n private totalDependencyCount = 0;\n private totalFailedDependencyCount = 0;\n private totalExceptionCount = 0;\n private requestDuration = 0;\n private dependencyDuration = 0;\n private lastRequestDuration: { count: number; duration: number; time: number } = {\n count: 0,\n duration: 0,\n time: 0,\n };\n private lastRequestRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastFailedRequestRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastDependencyDuration: { count: number; duration: number; time: number } = {\n count: 0,\n duration: 0,\n time: 0,\n };\n private lastDependencyRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastFailedDependencyRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastExceptionRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastCpus:\n | {\n model: string;\n speed: number;\n times: { user: number; nice: number; sys: number; idle: number; irq: number };\n }[]\n | undefined;\n\n /**\n * Initializes a new instance of the StandardMetrics class.\n * @param config - Distro configuration.\n * @param options - Standard Metrics options.\n */\n constructor(config: InternalConfig) {\n this.config = config;\n let idGenerator = new RandomIdGenerator();\n const streamId = idGenerator.generateTraceId();\n const machineName = os.hostname();\n const instance = getCloudRoleInstance(this.config.resource);\n const roleName = getCloudRole(this.config.resource);\n const version = getSdkVersion();\n this.baseMonitoringDataPoint = {\n version: version,\n invariantVersion: 1,\n instance: instance,\n roleName: roleName,\n machineName: machineName,\n streamId: streamId,\n performanceCollectionSupported: true,\n isWebApp: process.env[\"WEBSITE_SITE_NAME\"] ? true : false,\n };\n const parsedConnectionString = ConnectionStringParser.parse(\n this.config.azureMonitorExporterOptions.connectionString,\n );\n this.pingSender = new QuickpulseSender({\n endpointUrl: parsedConnectionString.liveendpoint || DEFAULT_LIVEMETRICS_ENDPOINT,\n instrumentationKey: parsedConnectionString.instrumentationkey || \"\",\n });\n let exporterOptions: QuickpulseExporterOptions = {\n endpointUrl: parsedConnectionString.liveendpoint || DEFAULT_LIVEMETRICS_ENDPOINT,\n instrumentationKey: parsedConnectionString.instrumentationkey || \"\",\n postCallback: this.quickPulseDone.bind(this),\n getDocumentsFn: this.getDocuments.bind(this),\n baseMonitoringDataPoint: this.baseMonitoringDataPoint,\n };\n this.quickpulseExporter = new QuickpulseMetricExporter(exporterOptions);\n this.isCollectingData = false;\n this.pingInterval = PING_INTERVAL; // Default\n this.postInterval = POST_INTERVAL;\n this.handle = <any>setTimeout(this.goQuickpulse.bind(this), this.pingInterval);\n this.handle.unref(); // Don't block apps from terminating\n }\n\n public shutdown() {\n this.meterProvider?.shutdown();\n }\n\n private async goQuickpulse() {\n if (!this.isCollectingData) {\n // If not collecting, Ping\n try {\n let params: IsSubscribedOptionalParams = {\n transmissionTime: getTransmissionTime(),\n monitoringDataPoint: this.baseMonitoringDataPoint,\n };\n await context.with(suppressTracing(context.active()), async () => {\n let response = await this.pingSender.isSubscribed(params);\n this.quickPulseDone(response);\n });\n } catch (error) {\n this.quickPulseDone(undefined);\n }\n this.handle = <any>setTimeout(this.goQuickpulse.bind(this), this.pingInterval);\n this.handle.unref();\n }\n if (this.isCollectingData) {\n this.activateMetrics({ collectionInterval: this.postInterval });\n }\n }\n\n private async quickPulseDone(response: PublishResponse | IsSubscribedResponse | undefined) {\n if (!response) {\n if (!this.isCollectingData) {\n if (Date.now() - this.lastSuccessTime >= MAX_PING_WAIT_TIME) {\n this.pingInterval = FALLBACK_INTERVAL;\n }\n } else {\n if (Date.now() - this.lastSuccessTime >= MAX_POST_WAIT_TIME) {\n this.postInterval = FALLBACK_INTERVAL;\n this.deactivateMetrics();\n this.activateMetrics({ collectionInterval: this.postInterval });\n }\n }\n } else {\n this.postInterval = POST_INTERVAL;\n // Update using response if needed\n this.lastSuccessTime = Date.now();\n this.isCollectingData =\n response.xMsQpsSubscribed && response.xMsQpsSubscribed === \"true\" ? true : false;\n\n // If collecting was stoped\n if (!this.isCollectingData && this.meterProvider) {\n this.deactivateMetrics();\n this.handle = <any>setTimeout(this.goQuickpulse.bind(this), this.pingInterval);\n this.handle.unref();\n }\n\n const endpointRedirect = (response as IsSubscribedResponse).xMsQpsServiceEndpointRedirectV2;\n if (endpointRedirect) {\n this.pingSender.handlePermanentRedirect(endpointRedirect);\n this.quickpulseExporter.getSender().handlePermanentRedirect(endpointRedirect);\n }\n const pollingInterval = (response as IsSubscribedResponse).xMsQpsServicePollingIntervalHint;\n if (pollingInterval) {\n this.pingInterval = Number(pollingInterval);\n } else {\n this.pingInterval = PING_INTERVAL;\n }\n }\n }\n\n // Activate live metrics collection\n public activateMetrics(options?: { collectionInterval: number }) {\n if (this.meterProvider) {\n return;\n }\n this.lastCpus = os.cpus();\n this.totalDependencyCount = 0;\n this.totalExceptionCount = 0;\n this.totalFailedDependencyCount = 0;\n this.totalFailedRequestCount = 0;\n this.totalRequestCount = 0;\n this.requestDuration = 0;\n this.dependencyDuration = 0;\n this.lastRequestDuration = { count: 0, duration: 0, time: 0 };\n this.lastRequestRate = { count: 0, time: 0 };\n this.lastFailedRequestRate = { count: 0, time: 0 };\n this.lastDependencyDuration = { count: 0, duration: 0, time: 0 };\n this.lastDependencyRate = { count: 0, time: 0 };\n this.lastFailedDependencyRate = { count: 0, time: 0 };\n this.lastExceptionRate = { count: 0, time: 0 };\n\n const metricReaderOptions: PeriodicExportingMetricReaderOptions = {\n exporter: this.quickpulseExporter,\n exportIntervalMillis: options?.collectionInterval,\n };\n this.metricReader = new PeriodicExportingMetricReader(metricReaderOptions);\n const meterProviderConfig: MeterProviderOptions = {\n resource: this.config.resource,\n readers: [this.metricReader],\n };\n this.meterProvider = new MeterProvider(meterProviderConfig);\n this.meter = this.meterProvider.getMeter(\"AzureMonitorLiveMetricsMeter\");\n this.requestDurationGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.REQUEST_DURATION,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.requestRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.REQUEST_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.requestFailedRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.REQUEST_FAILURE_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.dependencyDurationGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.DEPENDENCY_DURATION,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.dependencyRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.DEPENDENCY_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.dependencyFailedRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.DEPENDENCY_FAILURE_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n\n this.memoryCommitedGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.COMMITTED_BYTES,\n {\n valueType: ValueType.INT,\n },\n );\n\n this.processorTimeGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.PROCESSOR_TIME,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.exceptionsRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.EXCEPTION_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n\n this.requestDurationGauge.addCallback(this.getRequestDuration.bind(this));\n this.requestRateGauge.addCallback(this.getRequestRate.bind(this));\n this.requestFailedRateGauge.addCallback(this.getRequestFailedRate.bind(this));\n this.dependencyDurationGauge.addCallback(this.getDependencyDuration.bind(this));\n this.dependencyRateGauge.addCallback(this.getDependencyRate.bind(this));\n this.dependencyFailedRateGauge.addCallback(this.getDependencyFailedRate.bind(this));\n this.exceptionsRateGauge.addCallback(this.getExceptionRate.bind(this));\n this.memoryCommitedGauge.addCallback(this.getCommitedMemory.bind(this));\n this.processorTimeGauge.addCallback(this.getProcessorTime.bind(this));\n }\n\n /**\n * Deactivate metric collection\n */\n public deactivateMetrics() {\n this.documents = [];\n this.meterProvider?.shutdown();\n this.meterProvider = undefined;\n }\n\n /**\n * Force flush Meter Provider.\n */\n public async flush(): Promise<void> {\n await this.meterProvider?.forceFlush();\n }\n\n /**\n *Get OpenTelemetry MeterProvider\n */\n public getMeterProvider(): MeterProvider | undefined {\n return this.meterProvider;\n }\n\n public getDocuments(): DocumentIngress[] {\n return this.documents;\n }\n\n private addDocument(document: DocumentIngress) {\n if (document) {\n // Limit risk of memory leak by limiting doc length to something manageable\n if (this.documents.length > 20) {\n this.documents.shift(); // Remove oldest document\n }\n this.documents.push(document);\n }\n }\n\n /**\n * Record Span metrics\n * @internal\n */\n public recordSpan(span: ReadableSpan): void {\n if (this.isCollectingData) {\n // Add document and calculate metrics\n let document: Request | RemoteDependency = getSpanDocument(span);\n this.addDocument(document);\n const durationMs = hrTimeToMilliseconds(span.duration);\n let success = span.status.code !== SpanStatusCode.ERROR;\n\n if (span.kind === SpanKind.SERVER || span.kind === SpanKind.CONSUMER) {\n this.totalRequestCount++;\n this.requestDuration += durationMs;\n if (!success) {\n this.totalFailedRequestCount++;\n }\n } else {\n this.totalDependencyCount++;\n this.dependencyDuration += durationMs;\n if (!success) {\n this.totalFailedDependencyCount++;\n }\n }\n if (span.events) {\n span.events.forEach((event: TimedEvent) => {\n event.attributes = event.attributes || {};\n if (event.name === \"exception\") {\n this.totalExceptionCount++;\n }\n });\n }\n }\n }\n\n /**\n * Record LogRecord metrics, add attribute so data is not aggregated again in ingestion\n * @internal\n */\n public recordLog(logRecord: LogRecord): void {\n if (this.isCollectingData) {\n let document: Trace | Exception = getLogDocument(logRecord);\n this.addDocument(document);\n if (isExceptionTelemetry(logRecord)) {\n this.totalExceptionCount++;\n }\n }\n }\n\n private getRequestDuration(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const requestInterval = this.totalRequestCount - this.lastRequestDuration.count || 0;\n const durationInterval = this.requestDuration - this.lastRequestDuration.duration || 0;\n const elapsedMs = currentTime - this.lastRequestDuration.time;\n if (elapsedMs > 0) {\n const averageExecutionTime = durationInterval / requestInterval || 0; // default to 0 in case no requests in this interval\n observableResult.observe(averageExecutionTime);\n }\n this.lastRequestDuration = {\n count: this.totalRequestCount,\n duration: this.requestDuration,\n time: currentTime,\n };\n }\n\n private getRequestRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalRequests = this.totalRequestCount - this.lastRequestRate.count || 0;\n const elapsedMs = currentTime - this.lastRequestRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalRequests / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastRequestRate = {\n count: this.totalRequestCount,\n time: currentTime,\n };\n }\n\n private getRequestFailedRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalRequests = this.totalFailedRequestCount - this.lastFailedRequestRate.count || 0;\n const elapsedMs = currentTime - this.lastFailedRequestRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalRequests / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastFailedRequestRate = {\n count: this.totalFailedRequestCount,\n time: currentTime,\n };\n }\n\n private getDependencyDuration(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const dependencyInterval = this.totalDependencyCount - this.lastDependencyDuration.count || 0;\n const durationInterval = this.dependencyDuration - this.lastDependencyDuration.duration || 0;\n const elapsedMs = currentTime - this.lastDependencyDuration.time;\n if (elapsedMs > 0) {\n const averageExecutionTime = durationInterval / dependencyInterval || 0; // default to 0 in case no dependencies in this interval\n observableResult.observe(averageExecutionTime);\n }\n this.lastDependencyDuration = {\n count: this.totalDependencyCount,\n duration: this.dependencyDuration,\n time: currentTime,\n };\n }\n\n private getDependencyRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalData = this.totalDependencyCount - this.lastDependencyRate.count || 0;\n const elapsedMs = currentTime - this.lastDependencyRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalData / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastDependencyRate = {\n count: this.totalDependencyCount,\n time: currentTime,\n };\n }\n\n private getDependencyFailedRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalData = this.totalFailedDependencyCount - this.lastFailedDependencyRate.count || 0;\n const elapsedMs = currentTime - this.lastFailedDependencyRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalData / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastFailedDependencyRate = {\n count: this.totalFailedDependencyCount,\n time: currentTime,\n };\n }\n\n private getExceptionRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalData = this.totalExceptionCount - this.lastExceptionRate.count || 0;\n const elapsedMs = currentTime - this.lastExceptionRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalData / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastExceptionRate = {\n count: this.totalExceptionCount,\n time: currentTime,\n };\n }\n\n private getCommitedMemory(observableResult: ObservableResult) {\n var freeMem = os.freemem();\n var committedMemory = os.totalmem() - freeMem;\n observableResult.observe(committedMemory);\n }\n\n private getTotalCombinedCpu(cpus: os.CpuInfo[], lastCpus: os.CpuInfo[]) {\n let totalUser = 0;\n let totalSys = 0;\n let totalNice = 0;\n let totalIdle = 0;\n let totalIrq = 0;\n for (let i = 0; !!cpus && i < cpus.length; i++) {\n const cpu = cpus[i];\n const lastCpu = lastCpus[i];\n const times = cpu.times;\n const lastTimes = lastCpu.times;\n // user cpu time (or) % CPU time spent in user space\n let user = times.user - lastTimes.user;\n user = user > 0 ? user : 0; // Avoid negative values\n totalUser += user;\n // system cpu time (or) % CPU time spent in kernel space\n let sys = times.sys - lastTimes.sys;\n sys = sys > 0 ? sys : 0; // Avoid negative values\n totalSys += sys;\n // user nice cpu time (or) % CPU time spent on low priority processes\n let nice = times.nice - lastTimes.nice;\n nice = nice > 0 ? nice : 0; // Avoid negative values\n totalNice += nice;\n // idle cpu time (or) % CPU time spent idle\n let idle = times.idle - lastTimes.idle;\n idle = idle > 0 ? idle : 0; // Avoid negative values\n totalIdle += idle;\n // irq (or) % CPU time spent servicing/handling hardware interrupts\n let irq = times.irq - lastTimes.irq;\n irq = irq > 0 ? irq : 0; // Avoid negative values\n totalIrq += irq;\n }\n const combinedTotal = totalUser + totalSys + totalNice + totalIdle + totalIrq;\n return {\n combinedTotal: combinedTotal,\n totalUser: totalUser,\n totalIdle: totalIdle,\n };\n }\n\n private getProcessorTime(observableResult: ObservableResult) {\n // this reports total ms spent in each category since the OS was booted, to calculate percent it is necessary\n // to find the delta since the last measurement\n const cpus = os.cpus();\n if (cpus && cpus.length && this.lastCpus && cpus.length === this.lastCpus.length) {\n const cpuTotals = this.getTotalCombinedCpu(cpus, this.lastCpus);\n\n const value =\n cpuTotals.combinedTotal > 0\n ? ((cpuTotals.combinedTotal - cpuTotals.totalIdle) / cpuTotals.combinedTotal) * 100\n : 0;\n observableResult.observe(value);\n }\n this.lastCpus = cpus;\n }\n}\n"]}
1
+ {"version":3,"file":"liveMetrics.js","sourceRoot":"","sources":["../../../../src/metrics/quickpulse/liveMetrics.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EACL,aAAa,EAEb,6BAA6B,GAE9B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAIL,QAAQ,EACR,cAAc,EACd,SAAS,EACT,OAAO,GACR,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAA4B,MAAM,+BAA+B,CAAC;AAE5F,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAYhD,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,cAAc,EACd,aAAa,EACb,eAAe,EACf,mBAAmB,GACpB,MAAM,SAAS,CAAC;AACjB,OAAO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license.\nimport * as os from \"os\";\nimport {\n MeterProvider,\n MeterProviderOptions,\n PeriodicExportingMetricReader,\n PeriodicExportingMetricReaderOptions,\n} from \"@opentelemetry/sdk-metrics\";\nimport { InternalConfig } from \"../../shared/config\";\nimport {\n Meter,\n ObservableGauge,\n ObservableResult,\n SpanKind,\n SpanStatusCode,\n ValueType,\n context,\n} from \"@opentelemetry/api\";\nimport { RandomIdGenerator, ReadableSpan, TimedEvent } from \"@opentelemetry/sdk-trace-base\";\nimport { LogRecord } from \"@opentelemetry/sdk-logs\";\nimport { isExceptionTelemetry } from \"../utils\";\nimport {\n DocumentIngress,\n Exception,\n MonitoringDataPoint,\n IsSubscribedOptionalParams,\n IsSubscribedResponse,\n PublishResponse,\n RemoteDependency,\n Request,\n Trace,\n} from \"../../generated\";\nimport {\n getCloudRole,\n getCloudRoleInstance,\n getLogDocument,\n getSdkVersion,\n getSpanDocument,\n getTransmissionTime,\n} from \"./utils\";\nimport { QuickpulseMetricExporter } from \"./export/exporter\";\nimport { QuickpulseSender } from \"./export/sender\";\nimport { ConnectionStringParser } from \"../../utils/connectionStringParser\";\nimport { DEFAULT_LIVEMETRICS_ENDPOINT } from \"../../types\";\nimport { QuickPulseOpenTelemetryMetricNames, QuickpulseExporterOptions } from \"./types\";\nimport { hrTimeToMilliseconds, suppressTracing } from \"@opentelemetry/core\";\nimport { getInstance } from \"../../utils/statsbeat\";\n\nconst POST_INTERVAL = 1000;\nconst MAX_POST_WAIT_TIME = 20000;\nconst PING_INTERVAL = 5000;\nconst MAX_PING_WAIT_TIME = 60000;\nconst FALLBACK_INTERVAL = 60000;\n\n/**\n * Azure Monitor Live Metrics\n * @internal\n */\nexport class LiveMetrics {\n private config: InternalConfig;\n private meterProvider: MeterProvider | undefined;\n private metricReader: PeriodicExportingMetricReader | undefined;\n private meter: Meter | undefined;\n private requestDurationGauge: ObservableGauge | undefined;\n private dependencyDurationGauge: ObservableGauge | undefined;\n private requestRateGauge: ObservableGauge | undefined;\n private requestFailedRateGauge: ObservableGauge | undefined;\n private dependencyRateGauge: ObservableGauge | undefined;\n private dependencyFailedRateGauge: ObservableGauge | undefined;\n private memoryCommitedGauge: ObservableGauge | undefined;\n private processorTimeGauge: ObservableGauge | undefined;\n private exceptionsRateGauge: ObservableGauge | undefined;\n\n private documents: DocumentIngress[] = [];\n private pingInterval: number;\n private postInterval: number;\n private quickpulseExporter: QuickpulseMetricExporter;\n private pingSender: QuickpulseSender;\n private isCollectingData: boolean;\n private lastSuccessTime: number = Date.now();\n private handle: NodeJS.Timer;\n // Monitoring data point with common properties\n private baseMonitoringDataPoint: MonitoringDataPoint;\n private totalRequestCount = 0;\n private totalFailedRequestCount = 0;\n private totalDependencyCount = 0;\n private totalFailedDependencyCount = 0;\n private totalExceptionCount = 0;\n private requestDuration = 0;\n private dependencyDuration = 0;\n private lastRequestDuration: { count: number; duration: number; time: number } = {\n count: 0,\n duration: 0,\n time: 0,\n };\n private lastRequestRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastFailedRequestRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastDependencyDuration: { count: number; duration: number; time: number } = {\n count: 0,\n duration: 0,\n time: 0,\n };\n private lastDependencyRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastFailedDependencyRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastExceptionRate: { count: number; time: number } = { count: 0, time: 0 };\n private lastCpus:\n | {\n model: string;\n speed: number;\n times: { user: number; nice: number; sys: number; idle: number; irq: number };\n }[]\n | undefined;\n private statsbeatOptionsUpdated = false;\n\n /**\n * Initializes a new instance of the StandardMetrics class.\n * @param config - Distro configuration.\n * @param options - Standard Metrics options.\n */\n constructor(config: InternalConfig) {\n this.config = config;\n let idGenerator = new RandomIdGenerator();\n const streamId = idGenerator.generateTraceId();\n const machineName = os.hostname();\n const instance = getCloudRoleInstance(this.config.resource);\n const roleName = getCloudRole(this.config.resource);\n const version = getSdkVersion();\n this.baseMonitoringDataPoint = {\n version: version,\n invariantVersion: 1,\n instance: instance,\n roleName: roleName,\n machineName: machineName,\n streamId: streamId,\n performanceCollectionSupported: true,\n isWebApp: process.env[\"WEBSITE_SITE_NAME\"] ? true : false,\n };\n const parsedConnectionString = ConnectionStringParser.parse(\n this.config.azureMonitorExporterOptions.connectionString,\n );\n this.pingSender = new QuickpulseSender({\n endpointUrl: parsedConnectionString.liveendpoint || DEFAULT_LIVEMETRICS_ENDPOINT,\n instrumentationKey: parsedConnectionString.instrumentationkey || \"\",\n });\n let exporterOptions: QuickpulseExporterOptions = {\n endpointUrl: parsedConnectionString.liveendpoint || DEFAULT_LIVEMETRICS_ENDPOINT,\n instrumentationKey: parsedConnectionString.instrumentationkey || \"\",\n postCallback: this.quickPulseDone.bind(this),\n getDocumentsFn: this.getDocuments.bind(this),\n baseMonitoringDataPoint: this.baseMonitoringDataPoint,\n };\n this.quickpulseExporter = new QuickpulseMetricExporter(exporterOptions);\n this.isCollectingData = false;\n this.pingInterval = PING_INTERVAL; // Default\n this.postInterval = POST_INTERVAL;\n this.handle = <any>setTimeout(this.goQuickpulse.bind(this), this.pingInterval);\n this.handle.unref(); // Don't block apps from terminating\n }\n\n public shutdown() {\n this.meterProvider?.shutdown();\n }\n\n private async goQuickpulse() {\n if (!this.isCollectingData) {\n // If not collecting, Ping\n try {\n let params: IsSubscribedOptionalParams = {\n transmissionTime: getTransmissionTime(),\n monitoringDataPoint: this.baseMonitoringDataPoint,\n };\n await context.with(suppressTracing(context.active()), async () => {\n let response = await this.pingSender.isSubscribed(params);\n this.quickPulseDone(response);\n });\n } catch (error) {\n this.quickPulseDone(undefined);\n }\n this.handle = <any>setTimeout(this.goQuickpulse.bind(this), this.pingInterval);\n this.handle.unref();\n }\n if (this.isCollectingData) {\n this.activateMetrics({ collectionInterval: this.postInterval });\n }\n }\n\n private async quickPulseDone(response: PublishResponse | IsSubscribedResponse | undefined) {\n if (!response) {\n if (!this.isCollectingData) {\n if (Date.now() - this.lastSuccessTime >= MAX_PING_WAIT_TIME) {\n this.pingInterval = FALLBACK_INTERVAL;\n }\n } else {\n if (Date.now() - this.lastSuccessTime >= MAX_POST_WAIT_TIME) {\n this.postInterval = FALLBACK_INTERVAL;\n this.deactivateMetrics();\n this.activateMetrics({ collectionInterval: this.postInterval });\n }\n }\n } else {\n this.postInterval = POST_INTERVAL;\n // Update using response if needed\n this.lastSuccessTime = Date.now();\n this.isCollectingData =\n response.xMsQpsSubscribed && response.xMsQpsSubscribed === \"true\" ? true : false;\n\n // If collecting was stoped\n if (!this.isCollectingData && this.meterProvider) {\n this.deactivateMetrics();\n this.handle = <any>setTimeout(this.goQuickpulse.bind(this), this.pingInterval);\n this.handle.unref();\n }\n\n const endpointRedirect = (response as IsSubscribedResponse).xMsQpsServiceEndpointRedirectV2;\n if (endpointRedirect) {\n this.pingSender.handlePermanentRedirect(endpointRedirect);\n this.quickpulseExporter.getSender().handlePermanentRedirect(endpointRedirect);\n }\n const pollingInterval = (response as IsSubscribedResponse).xMsQpsServicePollingIntervalHint;\n if (pollingInterval) {\n this.pingInterval = Number(pollingInterval);\n } else {\n this.pingInterval = PING_INTERVAL;\n }\n }\n }\n\n // Activate live metrics collection\n public activateMetrics(options?: { collectionInterval: number }) {\n if (this.meterProvider) {\n return;\n }\n // Turn on live metrics active collection for statsbeat\n if (!this.statsbeatOptionsUpdated) {\n getInstance().setStatsbeatFeatures({ liveMetrics: true });\n this.statsbeatOptionsUpdated = true;\n }\n this.lastCpus = os.cpus();\n this.totalDependencyCount = 0;\n this.totalExceptionCount = 0;\n this.totalFailedDependencyCount = 0;\n this.totalFailedRequestCount = 0;\n this.totalRequestCount = 0;\n this.requestDuration = 0;\n this.dependencyDuration = 0;\n this.lastRequestDuration = { count: 0, duration: 0, time: 0 };\n this.lastRequestRate = { count: 0, time: 0 };\n this.lastFailedRequestRate = { count: 0, time: 0 };\n this.lastDependencyDuration = { count: 0, duration: 0, time: 0 };\n this.lastDependencyRate = { count: 0, time: 0 };\n this.lastFailedDependencyRate = { count: 0, time: 0 };\n this.lastExceptionRate = { count: 0, time: 0 };\n\n const metricReaderOptions: PeriodicExportingMetricReaderOptions = {\n exporter: this.quickpulseExporter,\n exportIntervalMillis: options?.collectionInterval,\n };\n this.metricReader = new PeriodicExportingMetricReader(metricReaderOptions);\n const meterProviderConfig: MeterProviderOptions = {\n resource: this.config.resource,\n readers: [this.metricReader],\n };\n this.meterProvider = new MeterProvider(meterProviderConfig);\n this.meter = this.meterProvider.getMeter(\"AzureMonitorLiveMetricsMeter\");\n this.requestDurationGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.REQUEST_DURATION,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.requestRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.REQUEST_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.requestFailedRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.REQUEST_FAILURE_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.dependencyDurationGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.DEPENDENCY_DURATION,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.dependencyRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.DEPENDENCY_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.dependencyFailedRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.DEPENDENCY_FAILURE_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n\n this.memoryCommitedGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.COMMITTED_BYTES,\n {\n valueType: ValueType.INT,\n },\n );\n\n this.processorTimeGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.PROCESSOR_TIME,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n this.exceptionsRateGauge = this.meter.createObservableGauge(\n QuickPulseOpenTelemetryMetricNames.EXCEPTION_RATE,\n {\n valueType: ValueType.DOUBLE,\n },\n );\n\n this.requestDurationGauge.addCallback(this.getRequestDuration.bind(this));\n this.requestRateGauge.addCallback(this.getRequestRate.bind(this));\n this.requestFailedRateGauge.addCallback(this.getRequestFailedRate.bind(this));\n this.dependencyDurationGauge.addCallback(this.getDependencyDuration.bind(this));\n this.dependencyRateGauge.addCallback(this.getDependencyRate.bind(this));\n this.dependencyFailedRateGauge.addCallback(this.getDependencyFailedRate.bind(this));\n this.exceptionsRateGauge.addCallback(this.getExceptionRate.bind(this));\n this.memoryCommitedGauge.addCallback(this.getCommitedMemory.bind(this));\n this.processorTimeGauge.addCallback(this.getProcessorTime.bind(this));\n }\n\n /**\n * Deactivate metric collection\n */\n public deactivateMetrics() {\n this.documents = [];\n this.meterProvider?.shutdown();\n this.meterProvider = undefined;\n }\n\n /**\n * Force flush Meter Provider.\n */\n public async flush(): Promise<void> {\n await this.meterProvider?.forceFlush();\n }\n\n /**\n *Get OpenTelemetry MeterProvider\n */\n public getMeterProvider(): MeterProvider | undefined {\n return this.meterProvider;\n }\n\n public getDocuments(): DocumentIngress[] {\n return this.documents;\n }\n\n private addDocument(document: DocumentIngress) {\n if (document) {\n // Limit risk of memory leak by limiting doc length to something manageable\n if (this.documents.length > 20) {\n this.documents.shift(); // Remove oldest document\n }\n this.documents.push(document);\n }\n }\n\n /**\n * Record Span metrics\n * @internal\n */\n public recordSpan(span: ReadableSpan): void {\n if (this.isCollectingData) {\n // Add document and calculate metrics\n let document: Request | RemoteDependency = getSpanDocument(span);\n this.addDocument(document);\n const durationMs = hrTimeToMilliseconds(span.duration);\n let success = span.status.code !== SpanStatusCode.ERROR;\n\n if (span.kind === SpanKind.SERVER || span.kind === SpanKind.CONSUMER) {\n this.totalRequestCount++;\n this.requestDuration += durationMs;\n if (!success) {\n this.totalFailedRequestCount++;\n }\n } else {\n this.totalDependencyCount++;\n this.dependencyDuration += durationMs;\n if (!success) {\n this.totalFailedDependencyCount++;\n }\n }\n if (span.events) {\n span.events.forEach((event: TimedEvent) => {\n event.attributes = event.attributes || {};\n if (event.name === \"exception\") {\n this.totalExceptionCount++;\n }\n });\n }\n }\n }\n\n /**\n * Record LogRecord metrics, add attribute so data is not aggregated again in ingestion\n * @internal\n */\n public recordLog(logRecord: LogRecord): void {\n if (this.isCollectingData) {\n let document: Trace | Exception = getLogDocument(logRecord);\n this.addDocument(document);\n if (isExceptionTelemetry(logRecord)) {\n this.totalExceptionCount++;\n }\n }\n }\n\n private getRequestDuration(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const requestInterval = this.totalRequestCount - this.lastRequestDuration.count || 0;\n const durationInterval = this.requestDuration - this.lastRequestDuration.duration || 0;\n const elapsedMs = currentTime - this.lastRequestDuration.time;\n if (elapsedMs > 0) {\n const averageExecutionTime = durationInterval / requestInterval || 0; // default to 0 in case no requests in this interval\n observableResult.observe(averageExecutionTime);\n }\n this.lastRequestDuration = {\n count: this.totalRequestCount,\n duration: this.requestDuration,\n time: currentTime,\n };\n }\n\n private getRequestRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalRequests = this.totalRequestCount - this.lastRequestRate.count || 0;\n const elapsedMs = currentTime - this.lastRequestRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalRequests / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastRequestRate = {\n count: this.totalRequestCount,\n time: currentTime,\n };\n }\n\n private getRequestFailedRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalRequests = this.totalFailedRequestCount - this.lastFailedRequestRate.count || 0;\n const elapsedMs = currentTime - this.lastFailedRequestRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalRequests / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastFailedRequestRate = {\n count: this.totalFailedRequestCount,\n time: currentTime,\n };\n }\n\n private getDependencyDuration(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const dependencyInterval = this.totalDependencyCount - this.lastDependencyDuration.count || 0;\n const durationInterval = this.dependencyDuration - this.lastDependencyDuration.duration || 0;\n const elapsedMs = currentTime - this.lastDependencyDuration.time;\n if (elapsedMs > 0) {\n const averageExecutionTime = durationInterval / dependencyInterval || 0; // default to 0 in case no dependencies in this interval\n observableResult.observe(averageExecutionTime);\n }\n this.lastDependencyDuration = {\n count: this.totalDependencyCount,\n duration: this.dependencyDuration,\n time: currentTime,\n };\n }\n\n private getDependencyRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalData = this.totalDependencyCount - this.lastDependencyRate.count || 0;\n const elapsedMs = currentTime - this.lastDependencyRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalData / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastDependencyRate = {\n count: this.totalDependencyCount,\n time: currentTime,\n };\n }\n\n private getDependencyFailedRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalData = this.totalFailedDependencyCount - this.lastFailedDependencyRate.count || 0;\n const elapsedMs = currentTime - this.lastFailedDependencyRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalData / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastFailedDependencyRate = {\n count: this.totalFailedDependencyCount,\n time: currentTime,\n };\n }\n\n private getExceptionRate(observableResult: ObservableResult) {\n const currentTime = +new Date();\n const intervalData = this.totalExceptionCount - this.lastExceptionRate.count || 0;\n const elapsedMs = currentTime - this.lastExceptionRate.time;\n if (elapsedMs > 0) {\n const elapsedSeconds = elapsedMs / 1000;\n const dataPerSec = intervalData / elapsedSeconds;\n observableResult.observe(dataPerSec);\n }\n this.lastExceptionRate = {\n count: this.totalExceptionCount,\n time: currentTime,\n };\n }\n\n private getCommitedMemory(observableResult: ObservableResult) {\n var freeMem = os.freemem();\n var committedMemory = os.totalmem() - freeMem;\n observableResult.observe(committedMemory);\n }\n\n private getTotalCombinedCpu(cpus: os.CpuInfo[], lastCpus: os.CpuInfo[]) {\n let totalUser = 0;\n let totalSys = 0;\n let totalNice = 0;\n let totalIdle = 0;\n let totalIrq = 0;\n for (let i = 0; !!cpus && i < cpus.length; i++) {\n const cpu = cpus[i];\n const lastCpu = lastCpus[i];\n const times = cpu.times;\n const lastTimes = lastCpu.times;\n // user cpu time (or) % CPU time spent in user space\n let user = times.user - lastTimes.user;\n user = user > 0 ? user : 0; // Avoid negative values\n totalUser += user;\n // system cpu time (or) % CPU time spent in kernel space\n let sys = times.sys - lastTimes.sys;\n sys = sys > 0 ? sys : 0; // Avoid negative values\n totalSys += sys;\n // user nice cpu time (or) % CPU time spent on low priority processes\n let nice = times.nice - lastTimes.nice;\n nice = nice > 0 ? nice : 0; // Avoid negative values\n totalNice += nice;\n // idle cpu time (or) % CPU time spent idle\n let idle = times.idle - lastTimes.idle;\n idle = idle > 0 ? idle : 0; // Avoid negative values\n totalIdle += idle;\n // irq (or) % CPU time spent servicing/handling hardware interrupts\n let irq = times.irq - lastTimes.irq;\n irq = irq > 0 ? irq : 0; // Avoid negative values\n totalIrq += irq;\n }\n const combinedTotal = totalUser + totalSys + totalNice + totalIdle + totalIrq;\n return {\n combinedTotal: combinedTotal,\n totalUser: totalUser,\n totalIdle: totalIdle,\n };\n }\n\n private getProcessorTime(observableResult: ObservableResult) {\n // this reports total ms spent in each category since the OS was booted, to calculate percent it is necessary\n // to find the delta since the last measurement\n const cpus = os.cpus();\n if (cpus && cpus.length && this.lastCpus && cpus.length === this.lastCpus.length) {\n const cpuTotals = this.getTotalCombinedCpu(cpus, this.lastCpus);\n\n const value =\n cpuTotals.combinedTotal > 0\n ? ((cpuTotals.combinedTotal - cpuTotals.totalIdle) / cpuTotals.combinedTotal) * 100\n : 0;\n observableResult.observe(value);\n }\n this.lastCpus = cpus;\n }\n}\n"]}
@@ -27,6 +27,7 @@ export class InternalConfig {
27
27
  this.samplingRatio = 1;
28
28
  this.enableLiveMetrics = false;
29
29
  this.enableStandardMetrics = true;
30
+ this.enableTraceBasedSamplingForLogs = true;
30
31
  this.instrumentationOptions = {
31
32
  http: { enabled: true },
32
33
  azureSdk: { enabled: false },
@@ -48,8 +49,16 @@ export class InternalConfig {
48
49
  this.resource = Object.assign(this.resource, options.resource);
49
50
  this.samplingRatio = options.samplingRatio || this.samplingRatio;
50
51
  this.browserSdkLoaderOptions = Object.assign(this.browserSdkLoaderOptions, options.browserSdkLoaderOptions);
51
- this.enableLiveMetrics = options.enableLiveMetrics || this.enableLiveMetrics;
52
- this.enableStandardMetrics = options.enableStandardMetrics || this.enableStandardMetrics;
52
+ this.enableLiveMetrics =
53
+ options.enableLiveMetrics != undefined ? options.enableLiveMetrics : this.enableLiveMetrics;
54
+ this.enableStandardMetrics =
55
+ options.enableStandardMetrics != undefined
56
+ ? options.enableStandardMetrics
57
+ : this.enableStandardMetrics;
58
+ this.enableTraceBasedSamplingForLogs =
59
+ options.enableTraceBasedSamplingForLogs != undefined
60
+ ? options.enableTraceBasedSamplingForLogs
61
+ : this.enableTraceBasedSamplingForLogs;
53
62
  }
54
63
  // JSON configuration will take precedence over other settings
55
64
  this._mergeConfig();
@@ -68,6 +77,10 @@ export class InternalConfig {
68
77
  jsonConfig.enableStandardMetrics !== undefined
69
78
  ? jsonConfig.enableStandardMetrics
70
79
  : this.enableStandardMetrics;
80
+ this.enableTraceBasedSamplingForLogs =
81
+ jsonConfig.enableTraceBasedSamplingForLogs !== undefined
82
+ ? jsonConfig.enableTraceBasedSamplingForLogs
83
+ : this.enableTraceBasedSamplingForLogs;
71
84
  this.azureMonitorExporterOptions = Object.assign(this.azureMonitorExporterOptions, jsonConfig.azureMonitorExporterOptions);
72
85
  this.instrumentationOptions = Object.assign(this.instrumentationOptions, jsonConfig.instrumentationOptions);
73
86
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/shared/config.ts"],"names":[],"mappings":"AAAA,uCAA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;YACrC,SAAS,EAAE,CAAC,eAAe,CAAC;SAC7B,CAAC,CAAC;QACH,IAAI,UAAU,CAAC,sBAAsB,EAAE,CAAC;YACtC,MAAA,UAAU,CAAC,sBAAsB,2DAAK,IAAI,CAAC,GAAG,EAAE;gBAC9C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,UAAU,CAAa,CAAC;YAChE,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n Resource,\n ResourceDetectionConfig,\n detectResourcesSync,\n envDetectorSync,\n} from \"@opentelemetry/resources\";\nimport {\n BrowserSdkLoaderOptions,\n AzureMonitorOpenTelemetryOptions,\n InstrumentationOptions,\n} from \"../types\";\nimport { AzureMonitorExporterOptions } from \"@azure/monitor-opentelemetry-exporter\";\nimport { JsonConfig } from \"./jsonConfig\";\nimport { Logger } from \"./logging\";\nimport {\n azureAppServiceDetector,\n azureFunctionsDetector,\n azureVmDetector,\n} from \"@opentelemetry/resource-detector-azure\";\n\n/**\n * Azure Monitor OpenTelemetry Client Configuration\n */\nexport class InternalConfig implements AzureMonitorOpenTelemetryOptions {\n /** The rate of telemetry items tracked that should be transmitted (Default 1.0) */\n public samplingRatio: number;\n /** Azure Monitor Exporter Configuration */\n public azureMonitorExporterOptions: AzureMonitorExporterOptions;\n /**\n * OpenTelemetry Instrumentations configuration included as part of Azure Monitor (azureSdk, http, mongoDb, mySql, postgreSql, redis, redis4)\n */\n public instrumentationOptions: InstrumentationOptions;\n /** Enable Live Metrics feature */\n enableLiveMetrics?: boolean;\n /** Enable Standard Metrics feature */\n enableStandardMetrics?: boolean;\n\n private _resource: Resource = Resource.empty();\n\n public set resource(resource: Resource) {\n this._resource = this._resource.merge(resource);\n }\n\n /**\n *Get OpenTelemetry Resource\n */\n public get resource(): Resource {\n return this._resource;\n }\n\n public browserSdkLoaderOptions: BrowserSdkLoaderOptions;\n\n /**\n * Initializes a new instance of the AzureMonitorOpenTelemetryOptions class.\n */\n constructor(options?: AzureMonitorOpenTelemetryOptions) {\n // Default values\n this.azureMonitorExporterOptions = {};\n this.samplingRatio = 1;\n this.enableLiveMetrics = false;\n this.enableStandardMetrics = true;\n this.instrumentationOptions = {\n http: { enabled: true },\n azureSdk: { enabled: false },\n mongoDb: { enabled: false },\n mySql: { enabled: false },\n postgreSql: { enabled: false },\n redis: { enabled: false },\n redis4: { enabled: false },\n };\n this._setDefaultResource();\n this.browserSdkLoaderOptions = {\n enabled: false,\n connectionString: \"\",\n };\n\n if (options) {\n // Merge default with provided options\n this.azureMonitorExporterOptions = Object.assign(\n this.azureMonitorExporterOptions,\n options.azureMonitorExporterOptions,\n );\n this.instrumentationOptions = Object.assign(\n this.instrumentationOptions,\n options.instrumentationOptions,\n );\n this.resource = Object.assign(this.resource, options.resource);\n this.samplingRatio = options.samplingRatio || this.samplingRatio;\n this.browserSdkLoaderOptions = Object.assign(\n this.browserSdkLoaderOptions,\n options.browserSdkLoaderOptions,\n );\n this.enableLiveMetrics = options.enableLiveMetrics || this.enableLiveMetrics;\n this.enableStandardMetrics = options.enableStandardMetrics || this.enableStandardMetrics;\n }\n // JSON configuration will take precedence over other settings\n this._mergeConfig();\n }\n\n private _mergeConfig() {\n try {\n const jsonConfig = JsonConfig.getInstance();\n this.samplingRatio =\n jsonConfig.samplingRatio !== undefined ? jsonConfig.samplingRatio : this.samplingRatio;\n this.browserSdkLoaderOptions = Object.assign(\n this.browserSdkLoaderOptions,\n jsonConfig.browserSdkLoaderOptions,\n );\n this.enableLiveMetrics =\n jsonConfig.enableLiveMetrics !== undefined\n ? jsonConfig.enableLiveMetrics\n : this.enableLiveMetrics;\n this.enableStandardMetrics =\n jsonConfig.enableStandardMetrics !== undefined\n ? jsonConfig.enableStandardMetrics\n : this.enableStandardMetrics;\n this.azureMonitorExporterOptions = Object.assign(\n this.azureMonitorExporterOptions,\n jsonConfig.azureMonitorExporterOptions,\n );\n this.instrumentationOptions = Object.assign(\n this.instrumentationOptions,\n jsonConfig.instrumentationOptions,\n );\n } catch (error) {\n Logger.getInstance().error(\"Failed to load JSON config file values.\", error);\n }\n }\n\n private _setDefaultResource(): void {\n let resource = Resource.default();\n // Load resource attributes from env\n const detectResourceConfig: ResourceDetectionConfig = {\n detectors: [envDetectorSync],\n };\n const envResource = detectResourcesSync(detectResourceConfig);\n resource = resource.merge(envResource) as Resource;\n\n // Load resource attributes from Azure\n const azureResource: Resource = detectResourcesSync({\n detectors: [azureAppServiceDetector, azureFunctionsDetector],\n });\n this._resource = resource.merge(azureResource) as Resource;\n\n const vmResource = detectResourcesSync({\n detectors: [azureVmDetector],\n });\n if (vmResource.asyncAttributesPending) {\n vmResource.waitForAsyncAttributes?.().then(() => {\n this._resource = this._resource.merge(vmResource) as Resource;\n });\n }\n }\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/shared/config.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,QAAQ,EAER,mBAAmB,EACnB,eAAe,GAChB,MAAM,0BAA0B,CAAC;AAOlC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,eAAe,GAChB,MAAM,wCAAwC,CAAC;AAEhD;;GAEG;AACH,MAAM,OAAO,cAAc;IAkBzB,IAAW,QAAQ,CAAC,QAAkB;QACpC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAClD,CAAC;IAED;;OAEG;IACH,IAAW,QAAQ;QACjB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAID;;OAEG;IACH,YAAY,OAA0C;QAlB9C,cAAS,GAAa,QAAQ,CAAC,KAAK,EAAE,CAAC;QAmB7C,iBA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B,2DAAK,IAAI,CAAC,GAAG,EAAE;gBAC9C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,UAAU,CAAa,CAAC;YAChE,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n Resource,\n ResourceDetectionConfig,\n detectResourcesSync,\n envDetectorSync,\n} from \"@opentelemetry/resources\";\nimport {\n BrowserSdkLoaderOptions,\n AzureMonitorOpenTelemetryOptions,\n InstrumentationOptions,\n} from \"../types\";\nimport { AzureMonitorExporterOptions } from \"@azure/monitor-opentelemetry-exporter\";\nimport { JsonConfig } from \"./jsonConfig\";\nimport { Logger } from \"./logging\";\nimport {\n azureAppServiceDetector,\n azureFunctionsDetector,\n azureVmDetector,\n} from \"@opentelemetry/resource-detector-azure\";\n\n/**\n * Azure Monitor OpenTelemetry Client Configuration\n */\nexport class InternalConfig implements AzureMonitorOpenTelemetryOptions {\n /** The rate of telemetry items tracked that should be transmitted (Default 1.0) */\n public samplingRatio: number;\n /** Azure Monitor Exporter Configuration */\n public azureMonitorExporterOptions: AzureMonitorExporterOptions;\n /**\n * OpenTelemetry Instrumentations configuration included as part of Azure Monitor (azureSdk, http, mongoDb, mySql, postgreSql, redis, redis4)\n */\n public instrumentationOptions: InstrumentationOptions;\n /** Enable Live Metrics feature */\n enableLiveMetrics?: boolean;\n /** Enable Standard Metrics feature */\n enableStandardMetrics?: boolean;\n /** Enable log sampling based on trace (Default true) */\n enableTraceBasedSamplingForLogs?: boolean;\n\n private _resource: Resource = Resource.empty();\n\n public set resource(resource: Resource) {\n this._resource = this._resource.merge(resource);\n }\n\n /**\n *Get OpenTelemetry Resource\n */\n public get resource(): Resource {\n return this._resource;\n }\n\n public browserSdkLoaderOptions: BrowserSdkLoaderOptions;\n\n /**\n * Initializes a new instance of the AzureMonitorOpenTelemetryOptions class.\n */\n constructor(options?: AzureMonitorOpenTelemetryOptions) {\n // Default values\n this.azureMonitorExporterOptions = {};\n this.samplingRatio = 1;\n this.enableLiveMetrics = false;\n this.enableStandardMetrics = true;\n this.enableTraceBasedSamplingForLogs = true;\n this.instrumentationOptions = {\n http: { enabled: true },\n azureSdk: { enabled: false },\n mongoDb: { enabled: false },\n mySql: { enabled: false },\n postgreSql: { enabled: false },\n redis: { enabled: false },\n redis4: { enabled: false },\n };\n this._setDefaultResource();\n this.browserSdkLoaderOptions = {\n enabled: false,\n connectionString: \"\",\n };\n\n if (options) {\n // Merge default with provided options\n this.azureMonitorExporterOptions = Object.assign(\n this.azureMonitorExporterOptions,\n options.azureMonitorExporterOptions,\n );\n this.instrumentationOptions = Object.assign(\n this.instrumentationOptions,\n options.instrumentationOptions,\n );\n this.resource = Object.assign(this.resource, options.resource);\n this.samplingRatio = options.samplingRatio || this.samplingRatio;\n this.browserSdkLoaderOptions = Object.assign(\n this.browserSdkLoaderOptions,\n options.browserSdkLoaderOptions,\n );\n this.enableLiveMetrics =\n options.enableLiveMetrics != undefined ? options.enableLiveMetrics : this.enableLiveMetrics;\n this.enableStandardMetrics =\n options.enableStandardMetrics != undefined\n ? options.enableStandardMetrics\n : this.enableStandardMetrics;\n this.enableTraceBasedSamplingForLogs =\n options.enableTraceBasedSamplingForLogs != undefined\n ? options.enableTraceBasedSamplingForLogs\n : this.enableTraceBasedSamplingForLogs;\n }\n // JSON configuration will take precedence over other settings\n this._mergeConfig();\n }\n\n private _mergeConfig() {\n try {\n const jsonConfig = JsonConfig.getInstance();\n this.samplingRatio =\n jsonConfig.samplingRatio !== undefined ? jsonConfig.samplingRatio : this.samplingRatio;\n this.browserSdkLoaderOptions = Object.assign(\n this.browserSdkLoaderOptions,\n jsonConfig.browserSdkLoaderOptions,\n );\n this.enableLiveMetrics =\n jsonConfig.enableLiveMetrics !== undefined\n ? jsonConfig.enableLiveMetrics\n : this.enableLiveMetrics;\n this.enableStandardMetrics =\n jsonConfig.enableStandardMetrics !== undefined\n ? jsonConfig.enableStandardMetrics\n : this.enableStandardMetrics;\n this.enableTraceBasedSamplingForLogs =\n jsonConfig.enableTraceBasedSamplingForLogs !== undefined\n ? jsonConfig.enableTraceBasedSamplingForLogs\n : this.enableTraceBasedSamplingForLogs;\n this.azureMonitorExporterOptions = Object.assign(\n this.azureMonitorExporterOptions,\n jsonConfig.azureMonitorExporterOptions,\n );\n this.instrumentationOptions = Object.assign(\n this.instrumentationOptions,\n jsonConfig.instrumentationOptions,\n );\n } catch (error) {\n Logger.getInstance().error(\"Failed to load JSON config file values.\", error);\n }\n }\n\n private _setDefaultResource(): void {\n let resource = Resource.default();\n // Load resource attributes from env\n const detectResourceConfig: ResourceDetectionConfig = {\n detectors: [envDetectorSync],\n };\n const envResource = detectResourcesSync(detectResourceConfig);\n resource = resource.merge(envResource) as Resource;\n\n // Load resource attributes from Azure\n const azureResource: Resource = detectResourcesSync({\n detectors: [azureAppServiceDetector, azureFunctionsDetector],\n });\n this._resource = resource.merge(azureResource) as Resource;\n\n const vmResource = detectResourcesSync({\n detectors: [azureVmDetector],\n });\n if (vmResource.asyncAttributesPending) {\n vmResource.waitForAsyncAttributes?.().then(() => {\n this._resource = this._resource.merge(vmResource) as Resource;\n });\n }\n }\n}\n"]}
@@ -57,6 +57,7 @@ export class JsonConfig {
57
57
  this.browserSdkLoaderOptions = jsonConfig.browserSdkLoaderOptions;
58
58
  this.enableLiveMetrics = jsonConfig.enableLiveMetrics;
59
59
  this.enableStandardMetrics = jsonConfig.enableStandardMetrics;
60
+ this.enableTraceBasedSamplingForLogs = jsonConfig.enableTraceBasedSamplingForLogs;
60
61
  }
61
62
  catch (err) {
62
63
  Logger.getInstance().info("Missing or invalid JSON config file: ", err);
@@ -1 +1 @@
1
- {"version":3,"file":"jsonConfig.js","sourceRoot":"","sources":["../../../src/shared/jsonConfig.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO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,CAAC,8CAA8C;gBACjG,CAAC;YACH,CAAC;YACD,IAAI,CAAC;gBACH,UAAU,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;YACtD,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,mCAAmC,EAAE,GAAG,CAAC,CAAC;YACtE,CAAC;QACH,CAAC;QACD,IAAI,CAAC;YACH,MAAM,UAAU,GAAqC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;YAC5E,IAAI,CAAC,2BAA2B,GAAG,UAAU,CAAC,2BAA2B,CAAC;YAC1E,IAAI,CAAC,aAAa,GAAG,UAAU,CAAC,aAAa,CAAC;YAC9C,IAAI,CAAC,sBAAsB,GAAG,UAAU,CAAC,sBAAsB,CAAC;YAChE,IAAI,CAAC,uBAAuB,GAAG,UAAU,CAAC,uBAAuB,CAAC;YAClE,IAAI,CAAC,iBAAiB,GAAG,UAAU,CAAC,iBAAiB,CAAC;YACtD,IAAI,CAAC,qBAAqB,GAAG,UAAU,CAAC,qBAAqB,CAAC;QAChE,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,uCAAuC,EAAE,GAAG,CAAC,CAAC;QAC1E,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport {\n BrowserSdkLoaderOptions,\n AzureMonitorOpenTelemetryOptions,\n InstrumentationOptions,\n} from \"../types\";\nimport { AzureMonitorExporterOptions } from \"@azure/monitor-opentelemetry-exporter\";\nimport { Logger } from \"./logging\";\n\nconst ENV_CONFIGURATION_FILE = \"APPLICATIONINSIGHTS_CONFIGURATION_FILE\";\nconst ENV_CONTENT = \"APPLICATIONINSIGHTS_CONFIGURATION_CONTENT\";\n\n/**\n * Azure Monitor OpenTelemetry Client Configuration through JSON File\n * @internal\n */\nexport class JsonConfig implements AzureMonitorOpenTelemetryOptions {\n /** The rate of telemetry items tracked that should be transmitted (Default 1.0) */\n public samplingRatio?: number;\n /** Azure Monitor Exporter Configuration */\n public azureMonitorExporterOptions?: AzureMonitorExporterOptions;\n /**\n * OpenTelemetry Instrumentations configuration included as part of Azure Monitor (azureSdk, http, mongoDb, mySql, postgreSql, redis, redis4)\n */\n public instrumentationOptions?: InstrumentationOptions;\n /** Enable Live Metrics feature */\n public enableLiveMetrics?: boolean;\n /** Enable Standard Metrics feature */\n public enableStandardMetrics?: boolean;\n\n public browserSdkLoaderOptions?: BrowserSdkLoaderOptions;\n\n private static _instance: JsonConfig;\n\n private _tempDir: string;\n\n /** Get Singleton instance */\n public static getInstance() {\n if (!JsonConfig._instance) {\n JsonConfig._instance = new JsonConfig();\n }\n return JsonConfig._instance;\n }\n\n /**\n * Initializes a new instance of the JsonConfig class.\n */\n constructor() {\n let jsonString = \"\";\n this._tempDir = \"\";\n const contentJsonConfig = process.env[ENV_CONTENT];\n // JSON string added directly in env variable\n if (contentJsonConfig) {\n jsonString = contentJsonConfig;\n }\n // JSON file\n else {\n let configFileName = \"applicationinsights.json\";\n let rootPath = path.join(__dirname, \"../../../\"); // Root of folder (__dirname = ../dist-esm/src)\n this._tempDir = path.join(rootPath, configFileName); // default\n let configFile = process.env[ENV_CONFIGURATION_FILE];\n if (configFile) {\n if (path.isAbsolute(configFile)) {\n this._tempDir = configFile;\n } else {\n this._tempDir = path.join(rootPath, configFile); // Relative path to applicationinsights folder\n }\n }\n try {\n jsonString = fs.readFileSync(this._tempDir, \"utf8\");\n } catch (err) {\n Logger.getInstance().info(\"Failed to read JSON config file: \", err);\n }\n }\n try {\n const jsonConfig: AzureMonitorOpenTelemetryOptions = JSON.parse(jsonString);\n this.azureMonitorExporterOptions = jsonConfig.azureMonitorExporterOptions;\n this.samplingRatio = jsonConfig.samplingRatio;\n this.instrumentationOptions = jsonConfig.instrumentationOptions;\n this.browserSdkLoaderOptions = jsonConfig.browserSdkLoaderOptions;\n this.enableLiveMetrics = jsonConfig.enableLiveMetrics;\n this.enableStandardMetrics = jsonConfig.enableStandardMetrics;\n } catch (err) {\n Logger.getInstance().info(\"Missing or invalid JSON config file: \", err);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"jsonConfig.js","sourceRoot":"","sources":["../../../src/shared/jsonConfig.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAO7B,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,MAAM,sBAAsB,GAAG,wCAAwC,CAAC;AACxE,MAAM,WAAW,GAAG,2CAA2C,CAAC;AAEhE;;;GAGG;AACH,MAAM,OAAO,UAAU;IAsBrB,6BAA6B;IACtB,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,CAAC;YAC1B,UAAU,CAAC,SAAS,GAAG,IAAI,UAAU,EAAE,CAAC;QAC1C,CAAC;QACD,OAAO,UAAU,CAAC,SAAS,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH;QACE,IAAI,UAAU,GAAG,EAAE,CAAC;QACpB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QACnB,MAAM,iBAAiB,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACnD,6CAA6C;QAC7C,IAAI,iBAAiB,EAAE,CAAC;YACtB,UAAU,GAAG,iBAAiB,CAAC;QACjC,CAAC;QACD,YAAY;aACP,CAAC;YACJ,IAAI,cAAc,GAAG,0BAA0B,CAAC;YAChD,IAAI,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC,+CAA+C;YACjG,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,I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IAAI,CAAC,uCAAuC,EAAE,GAAG,CAAC,CAAC;QAC1E,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport {\n BrowserSdkLoaderOptions,\n AzureMonitorOpenTelemetryOptions,\n InstrumentationOptions,\n} from \"../types\";\nimport { AzureMonitorExporterOptions } from \"@azure/monitor-opentelemetry-exporter\";\nimport { Logger } from \"./logging\";\n\nconst ENV_CONFIGURATION_FILE = \"APPLICATIONINSIGHTS_CONFIGURATION_FILE\";\nconst ENV_CONTENT = \"APPLICATIONINSIGHTS_CONFIGURATION_CONTENT\";\n\n/**\n * Azure Monitor OpenTelemetry Client Configuration through JSON File\n * @internal\n */\nexport class JsonConfig implements AzureMonitorOpenTelemetryOptions {\n /** The rate of telemetry items tracked that should be transmitted (Default 1.0) */\n public samplingRatio?: number;\n /** Azure Monitor Exporter Configuration */\n public azureMonitorExporterOptions?: AzureMonitorExporterOptions;\n /**\n * OpenTelemetry Instrumentations configuration included as part of Azure Monitor (azureSdk, http, mongoDb, mySql, postgreSql, redis, redis4)\n */\n public instrumentationOptions?: InstrumentationOptions;\n /** Enable Live Metrics feature */\n public enableLiveMetrics?: boolean;\n /** Enable Standard Metrics feature */\n public enableStandardMetrics?: boolean;\n /** Enable log sampling based on trace (Default true) */\n public enableTraceBasedSamplingForLogs?: boolean;\n\n public browserSdkLoaderOptions?: BrowserSdkLoaderOptions;\n\n private static _instance: JsonConfig;\n\n private _tempDir: string;\n\n /** Get Singleton instance */\n public static getInstance() {\n if (!JsonConfig._instance) {\n JsonConfig._instance = new JsonConfig();\n }\n return JsonConfig._instance;\n }\n\n /**\n * Initializes a new instance of the JsonConfig class.\n */\n constructor() {\n let jsonString = \"\";\n this._tempDir = \"\";\n const contentJsonConfig = process.env[ENV_CONTENT];\n // JSON string added directly in env variable\n if (contentJsonConfig) {\n jsonString = contentJsonConfig;\n }\n // JSON file\n else {\n let configFileName = \"applicationinsights.json\";\n let rootPath = path.join(__dirname, \"../../../\"); // Root of folder (__dirname = ../dist-esm/src)\n this._tempDir = path.join(rootPath, configFileName); // default\n let configFile = process.env[ENV_CONFIGURATION_FILE];\n if (configFile) {\n if (path.isAbsolute(configFile)) {\n this._tempDir = configFile;\n } else {\n this._tempDir = path.join(rootPath, configFile); // Relative path to applicationinsights folder\n }\n }\n try {\n jsonString = fs.readFileSync(this._tempDir, \"utf8\");\n } catch (err) {\n Logger.getInstance().info(\"Failed to read JSON config file: \", err);\n }\n }\n try {\n const jsonConfig: AzureMonitorOpenTelemetryOptions = JSON.parse(jsonString);\n this.azureMonitorExporterOptions = jsonConfig.azureMonitorExporterOptions;\n this.samplingRatio = jsonConfig.samplingRatio;\n this.instrumentationOptions = jsonConfig.instrumentationOptions;\n this.browserSdkLoaderOptions = jsonConfig.browserSdkLoaderOptions;\n this.enableLiveMetrics = jsonConfig.enableLiveMetrics;\n this.enableStandardMetrics = jsonConfig.enableStandardMetrics;\n this.enableTraceBasedSamplingForLogs = jsonConfig.enableTraceBasedSamplingForLogs;\n } catch (err) {\n Logger.getInstance().info(\"Missing or invalid JSON config file: \", err);\n }\n }\n}\n"]}
@@ -2,7 +2,7 @@
2
2
  // Licensed under the MIT license.
3
3
  // Copyright (c) Microsoft Corporation.
4
4
  // Licensed under the MIT license.
5
- export const AZURE_MONITOR_OPENTELEMETRY_VERSION = "1.3.0";
5
+ export const AZURE_MONITOR_OPENTELEMETRY_VERSION = "1.4.0";
6
6
  export const AZURE_MONITOR_STATSBEAT_FEATURES = "AZURE_MONITOR_STATSBEAT_FEATURES";
7
7
  export const AZURE_MONITOR_PREFIX = "AZURE_MONITOR_PREFIX";
8
8
  export const AZURE_MONITOR_AUTO_ATTACH = "AZURE_MONITOR_AUTO_ATTACH";
@@ -33,6 +33,7 @@ export var StatsbeatFeature;
33
33
  StatsbeatFeature[StatsbeatFeature["AAD_HANDLING"] = 2] = "AAD_HANDLING";
34
34
  StatsbeatFeature[StatsbeatFeature["BROWSER_SDK_LOADER"] = 4] = "BROWSER_SDK_LOADER";
35
35
  StatsbeatFeature[StatsbeatFeature["DISTRO"] = 8] = "DISTRO";
36
+ StatsbeatFeature[StatsbeatFeature["LIVE_METRICS"] = 16] = "LIVE_METRICS";
36
37
  })(StatsbeatFeature || (StatsbeatFeature = {}));
37
38
  export var StatsbeatInstrumentation;
38
39
  (function (StatsbeatInstrumentation) {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,uCAAuC;AACvC,kCAAkC;AAgElC,MAAM,CAAC,MAAM,mCAAmC,GAAG,OAAO,CAAC;AAC3D,MAAM,CAAC,MAAM,gCAAgC,GAAG,kCAAkC,CAAC;AACnF,MAAM,CAAC,MAAM,oBAAoB,GAAG,sBAAsB,CAAC;AAC3D,MAAM,CAAC,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AAErE,MAAM,CAAN,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,yCAAqB,CAAA;IACrB,gCAAY,CAAA;AACd,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,2CAA2C,CAAC;AAE7F;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAC9E;;;GAGG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,kDAAkD,CAAC;AAE/F,MAAM,CAAN,IAAY,gBAMX;AAND,WAAY,gBAAgB;IAC1B,uDAAQ,CAAA;IACR,mEAAc,CAAA;IACd,uEAAgB,CAAA;IAChB,mFAAsB,CAAA;IACtB,2DAAU,CAAA;AACZ,CAAC,EANW,gBAAgB,KAAhB,gBAAgB,QAM3B;AAED,MAAM,CAAN,IAAY,wBAQX;AARD,WAAY,wBAAwB;IAClC,uEAAQ,CAAA;IACR,mGAAsB,CAAA;IACtB,6EAAW,CAAA;IACX,yEAAS,CAAA;IACT,yEAAS,CAAA;IACT,gFAAa,CAAA;IACb,4EAAW,CAAA;AACb,CAAC,EARW,wBAAwB,KAAxB,wBAAwB,QAQnC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureMonitorExporterOptions } from \"@azure/monitor-opentelemetry-exporter\";\nimport { InstrumentationConfig } from \"@opentelemetry/instrumentation\";\nimport { Resource } from \"@opentelemetry/resources\";\nimport { LogRecordProcessor } from \"@opentelemetry/sdk-logs\";\nimport { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\n\n/**\n * Azure Monitor OpenTelemetry Options\n */\nexport interface AzureMonitorOpenTelemetryOptions {\n /** Azure Monitor Exporter Configuration */\n azureMonitorExporterOptions?: AzureMonitorExporterOptions;\n /** OpenTelemetry Resource */\n resource?: Resource;\n /** The rate of telemetry items tracked that should be transmitted (Default 1.0) */\n samplingRatio?: number;\n /** Enable Live Metrics feature */\n enableLiveMetrics?: boolean;\n /** Enable Standard Metrics feature */\n enableStandardMetrics?: boolean;\n /** OpenTelemetry Instrumentations options included as part of Azure Monitor (azureSdk, http, mongoDb, mySql, postgreSql, redis, redis4) */\n instrumentationOptions?: InstrumentationOptions;\n /** Application Insights Web Instrumentation options (enabled, connectionString, src, config)*/\n browserSdkLoaderOptions?: BrowserSdkLoaderOptions;\n /** An array of log record processors to register to the logger provider.*/\n logRecordProcessors?: LogRecordProcessor[];\n /** An array of span processors to register to the tracer provider.*/\n spanProcessors?: SpanProcessor[];\n}\n\n/**\n * OpenTelemetry Instrumentations Configuration interface\n */\nexport interface InstrumentationOptions {\n /** Azure SDK Instrumentation Config */\n azureSdk?: InstrumentationConfig;\n /** HTTP Instrumentation Config */\n http?: InstrumentationConfig;\n /** MongoDB Instrumentation Config */\n mongoDb?: InstrumentationConfig;\n /** MySQL Instrumentation Config */\n mySql?: InstrumentationConfig;\n /** PostgreSql Instrumentation Config */\n postgreSql?: InstrumentationConfig;\n /** Redis Instrumentation Config */\n redis?: InstrumentationConfig;\n /** Redis4 Instrumentation Config */\n redis4?: InstrumentationConfig;\n /** Bunyan Instrumentation Config */\n bunyan?: InstrumentationConfig;\n}\n\n/**\n * Application Insights Web Instrumentation Configuration interface\n */\nexport interface BrowserSdkLoaderOptions {\n /** Browser SDK Loader Enable */\n enabled?: boolean;\n /** Browser SDK Loader Connection String */\n connectionString?: string;\n}\n\nexport const AZURE_MONITOR_OPENTELEMETRY_VERSION = \"1.3.0\";\nexport const AZURE_MONITOR_STATSBEAT_FEATURES = \"AZURE_MONITOR_STATSBEAT_FEATURES\";\nexport const AZURE_MONITOR_PREFIX = \"AZURE_MONITOR_PREFIX\";\nexport const AZURE_MONITOR_AUTO_ATTACH = \"AZURE_MONITOR_AUTO_ATTACH\";\n\nexport enum AttachTypePrefix {\n INTEGRATED_AUTO = \"i\",\n MANUAL = \"m\",\n}\n\n/**\n * Default Browser SDK Loader Source\n * @internal\n */\nexport const BROWSER_SDK_LOADER_DEFAULT_SOURCE = \"https://js.monitor.azure.com/scripts/b/ai\";\n\n/**\n * Default Breeze endpoint.\n * @internal\n */\nexport const DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\n/**\n * Default Live Metrics endpoint.\n * @internal\n */\nexport const DEFAULT_LIVEMETRICS_ENDPOINT = \"https://global.livediagnostics.monitor.azure.com\";\n\nexport enum StatsbeatFeature {\n NONE = 0,\n DISK_RETRY = 1,\n AAD_HANDLING = 2,\n BROWSER_SDK_LOADER = 4,\n DISTRO = 8,\n}\n\nexport enum StatsbeatInstrumentation {\n NONE = 0,\n AZURE_CORE_TRACING = 1,\n MONGODB = 2,\n MYSQL = 4,\n REDIS = 8,\n POSTGRES = 16,\n BUNYAN = 32,\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,uCAAuC;AACvC,kCAAkC;AAqFlC,MAAM,CAAC,MAAM,mCAAmC,GAAG,OAAO,CAAC;AAC3D,MAAM,CAAC,MAAM,gCAAgC,GAAG,kCAAkC,CAAC;AACnF,MAAM,CAAC,MAAM,oBAAoB,GAAG,sBAAsB,CAAC;AAC3D,MAAM,CAAC,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AAErE,MAAM,CAAN,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,yCAAqB,CAAA;IACrB,gCAAY,CAAA;AACd,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,2CAA2C,CAAC;AAE7F;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAC9E;;;GAGG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,kDAAkD,CAAC;AAE/F,MAAM,CAAN,IAAY,gBAOX;AAPD,WAAY,gBAAgB;IAC1B,uDAAQ,CAAA;IACR,mEAAc,CAAA;IACd,uEAAgB,CAAA;IAChB,mFAAsB,CAAA;IACtB,2DAAU,CAAA;IACV,wEAAiB,CAAA;AACnB,CAAC,EAPW,gBAAgB,KAAhB,gBAAgB,QAO3B;AAED,MAAM,CAAN,IAAY,wBAQX;AARD,WAAY,wBAAwB;IAClC,uEAAQ,CAAA;IACR,mGAAsB,CAAA;IACtB,6EAAW,CAAA;IACX,yEAAS,CAAA;IACT,yEAAS,CAAA;IACT,gFAAa,CAAA;IACb,4EAAW,CAAA;AACb,CAAC,EARW,wBAAwB,KAAxB,wBAAwB,QAQnC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureMonitorExporterOptions } from \"@azure/monitor-opentelemetry-exporter\";\nimport { InstrumentationConfig } from \"@opentelemetry/instrumentation\";\nimport { Resource } from \"@opentelemetry/resources\";\nimport { LogRecordProcessor } from \"@opentelemetry/sdk-logs\";\nimport { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\n\n/**\n * Azure Monitor OpenTelemetry Options\n */\nexport interface AzureMonitorOpenTelemetryOptions {\n /** Azure Monitor Exporter Configuration */\n azureMonitorExporterOptions?: AzureMonitorExporterOptions;\n /** OpenTelemetry Resource */\n resource?: Resource;\n /** The rate of telemetry items tracked that should be transmitted (Default 1.0) */\n samplingRatio?: number;\n /** Enable Live Metrics feature (Default false)*/\n enableLiveMetrics?: boolean;\n /** Enable Standard Metrics feature (Default true)*/\n enableStandardMetrics?: boolean;\n /** Enable log sampling based on trace (Default true) */\n enableTraceBasedSamplingForLogs?: boolean;\n /** OpenTelemetry Instrumentations options included as part of Azure Monitor (azureSdk, http, mongoDb, mySql, postgreSql, redis, redis4) */\n instrumentationOptions?: InstrumentationOptions;\n /** Application Insights Web Instrumentation options (enabled, connectionString, src, config)*/\n browserSdkLoaderOptions?: BrowserSdkLoaderOptions;\n /** An array of log record processors to register to the logger provider.*/\n logRecordProcessors?: LogRecordProcessor[];\n /** An array of span processors to register to the tracer provider.*/\n spanProcessors?: SpanProcessor[];\n}\n\n/**\n * OpenTelemetry Instrumentations Configuration interface\n */\nexport interface InstrumentationOptions {\n /** Azure SDK Instrumentation Config */\n azureSdk?: InstrumentationConfig;\n /** HTTP Instrumentation Config */\n http?: InstrumentationConfig;\n /** MongoDB Instrumentation Config */\n mongoDb?: InstrumentationConfig;\n /** MySQL Instrumentation Config */\n mySql?: InstrumentationConfig;\n /** PostgreSql Instrumentation Config */\n postgreSql?: InstrumentationConfig;\n /** Redis Instrumentation Config */\n redis?: InstrumentationConfig;\n /** Redis4 Instrumentation Config */\n redis4?: InstrumentationConfig;\n /** Bunyan Instrumentation Config */\n bunyan?: InstrumentationConfig;\n}\n\n/**\n * Statsbeat Feature and Instrumentation Options interface\n * @internal\n */\nexport interface StatsbeatOptions {\n /** Instrumentations */\n azureSdk?: boolean;\n mongoDb?: boolean;\n mySql?: boolean;\n postgreSql?: boolean;\n redis?: boolean;\n bunyan?: boolean;\n /** Features */\n liveMetrics?: boolean;\n browserSdkLoader?: boolean;\n aadHandling?: boolean;\n diskRetry?: boolean;\n}\n\n/**\n * Application Insights Web Instrumentation Configuration interface\n */\nexport interface BrowserSdkLoaderOptions {\n /** Browser SDK Loader Enable */\n enabled?: boolean;\n /** Browser SDK Loader Connection String */\n connectionString?: string;\n}\n\nexport const AZURE_MONITOR_OPENTELEMETRY_VERSION = \"1.4.0\";\nexport const AZURE_MONITOR_STATSBEAT_FEATURES = \"AZURE_MONITOR_STATSBEAT_FEATURES\";\nexport const AZURE_MONITOR_PREFIX = \"AZURE_MONITOR_PREFIX\";\nexport const AZURE_MONITOR_AUTO_ATTACH = \"AZURE_MONITOR_AUTO_ATTACH\";\n\nexport enum AttachTypePrefix {\n INTEGRATED_AUTO = \"i\",\n MANUAL = \"m\",\n}\n\n/**\n * Default Browser SDK Loader Source\n * @internal\n */\nexport const BROWSER_SDK_LOADER_DEFAULT_SOURCE = \"https://js.monitor.azure.com/scripts/b/ai\";\n\n/**\n * Default Breeze endpoint.\n * @internal\n */\nexport const DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\n/**\n * Default Live Metrics endpoint.\n * @internal\n */\nexport const DEFAULT_LIVEMETRICS_ENDPOINT = \"https://global.livediagnostics.monitor.azure.com\";\n\nexport enum StatsbeatFeature {\n NONE = 0,\n DISK_RETRY = 1,\n AAD_HANDLING = 2,\n BROWSER_SDK_LOADER = 4,\n DISTRO = 8,\n LIVE_METRICS = 16,\n}\n\nexport enum StatsbeatInstrumentation {\n NONE = 0,\n AZURE_CORE_TRACING = 1,\n MONGODB = 2,\n MYSQL = 4,\n REDIS = 8,\n POSTGRES = 16,\n BUNYAN = 32,\n}\n"]}
@@ -0,0 +1,67 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { AZURE_MONITOR_STATSBEAT_FEATURES, StatsbeatFeature, StatsbeatInstrumentation, } from "../types";
4
+ import { Logger as InternalLogger } from "../shared/logging";
5
+ let instance;
6
+ class StatsbeatConfiguration {
7
+ constructor() {
8
+ // Initial Statsbeat options
9
+ this.currentStatsbeatOptions = {};
10
+ this.setStatsbeatFeatures = (statsbeatOptions) => {
11
+ // Merge old statsbeat options with new statsbeat options overriding any common properties
12
+ this.currentStatsbeatOptions = Object.assign(Object.assign({}, this.currentStatsbeatOptions), statsbeatOptions);
13
+ let instrumentationBitMap = StatsbeatInstrumentation.NONE;
14
+ if (statsbeatOptions.azureSdk === true) {
15
+ instrumentationBitMap |= StatsbeatInstrumentation.AZURE_CORE_TRACING;
16
+ }
17
+ if (statsbeatOptions.mongoDb === true) {
18
+ instrumentationBitMap |= StatsbeatInstrumentation.MONGODB;
19
+ }
20
+ if (statsbeatOptions.mySql === true) {
21
+ instrumentationBitMap |= StatsbeatInstrumentation.MYSQL;
22
+ }
23
+ if (statsbeatOptions.postgreSql === true) {
24
+ instrumentationBitMap |= StatsbeatInstrumentation.POSTGRES;
25
+ }
26
+ if (statsbeatOptions.redis === true) {
27
+ instrumentationBitMap |= StatsbeatInstrumentation.REDIS;
28
+ }
29
+ if (statsbeatOptions.bunyan === true) {
30
+ instrumentationBitMap |= StatsbeatInstrumentation.BUNYAN;
31
+ }
32
+ let featureBitMap = StatsbeatFeature.NONE;
33
+ featureBitMap |= StatsbeatFeature.DISTRO;
34
+ if (statsbeatOptions.browserSdkLoader === true) {
35
+ featureBitMap |= StatsbeatFeature.BROWSER_SDK_LOADER;
36
+ }
37
+ // Determines if the customer has activated the Live Metrics feature
38
+ if (statsbeatOptions.liveMetrics === true) {
39
+ featureBitMap |= StatsbeatFeature.LIVE_METRICS;
40
+ }
41
+ try {
42
+ const currentFeaturesBitMap = Number(process.env[AZURE_MONITOR_STATSBEAT_FEATURES]);
43
+ if (!isNaN(currentFeaturesBitMap)) {
44
+ featureBitMap |= currentFeaturesBitMap;
45
+ }
46
+ process.env[AZURE_MONITOR_STATSBEAT_FEATURES] = JSON.stringify({
47
+ instrumentation: instrumentationBitMap,
48
+ feature: featureBitMap,
49
+ });
50
+ }
51
+ catch (error) {
52
+ InternalLogger.getInstance().error("Failed call to JSON.stringify.", error);
53
+ }
54
+ };
55
+ }
56
+ }
57
+ /**
58
+ * Singleton Statsbeat instance.
59
+ * @internal
60
+ */
61
+ export function getInstance() {
62
+ if (!instance) {
63
+ instance = new StatsbeatConfiguration();
64
+ }
65
+ return instance;
66
+ }
67
+ //# sourceMappingURL=statsbeat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statsbeat.js","sourceRoot":"","sources":["../../../src/utils/statsbeat.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,gCAAgC,EAChC,gBAAgB,EAChB,wBAAwB,GAEzB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,MAAM,IAAI,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAE7D,IAAI,QAAgC,CAAC;AAErC,MAAM,sBAAsB;IAA5B;QACE,4BAA4B;QACpB,4BAAuB,GAAqB,EAAE,CAAC;QAEhD,yBAAoB,GAAG,CAAC,gBAAkC,EAAE,EAAE;YACnE,0FAA0F;YAC1F,IAAI,CAAC,uBAAuB,mCAAQ,IAAI,CAAC,uBAAuB,GAAK,gBAAgB,CAAE,CAAC;YAExF,IAAI,qBAAqB,GAAG,wBAAwB,CAAC,IAAI,CAAC;YAC1D,IAAI,gBAAgB,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;gBACvC,qBAAqB,IAAI,wBAAwB,CAAC,kBAAkB,CAAC;YACvE,CAAC;YACD,IAAI,gBAAgB,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;gBACtC,qBAAqB,IAAI,wBAAwB,CAAC,OAAO,CAAC;YAC5D,CAAC;YACD,IAAI,gBAAgB,CAAC,KAAK,KAAK,IAAI,E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AAK,CAAC,CAAC;YAC9E,CAAC;QACH,CAAC,CAAC;IACJ,CAAC;CAAA;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW;IACzB,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,QAAQ,GAAG,IAAI,sBAAsB,EAAE,CAAC;IAC1C,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AZURE_MONITOR_STATSBEAT_FEATURES,\n StatsbeatFeature,\n StatsbeatInstrumentation,\n StatsbeatOptions,\n} from \"../types\";\nimport { Logger as InternalLogger } from \"../shared/logging\";\n\nlet instance: StatsbeatConfiguration;\n\nclass StatsbeatConfiguration {\n // Initial Statsbeat options\n private currentStatsbeatOptions: StatsbeatOptions = {};\n\n public setStatsbeatFeatures = (statsbeatOptions: StatsbeatOptions) => {\n // Merge old statsbeat options with new statsbeat options overriding any common properties\n this.currentStatsbeatOptions = { ...this.currentStatsbeatOptions, ...statsbeatOptions };\n\n let instrumentationBitMap = StatsbeatInstrumentation.NONE;\n if (statsbeatOptions.azureSdk === true) {\n instrumentationBitMap |= StatsbeatInstrumentation.AZURE_CORE_TRACING;\n }\n if (statsbeatOptions.mongoDb === true) {\n instrumentationBitMap |= StatsbeatInstrumentation.MONGODB;\n }\n if (statsbeatOptions.mySql === true) {\n instrumentationBitMap |= StatsbeatInstrumentation.MYSQL;\n }\n if (statsbeatOptions.postgreSql === true) {\n instrumentationBitMap |= StatsbeatInstrumentation.POSTGRES;\n }\n if (statsbeatOptions.redis === true) {\n instrumentationBitMap |= StatsbeatInstrumentation.REDIS;\n }\n if (statsbeatOptions.bunyan === true) {\n instrumentationBitMap |= StatsbeatInstrumentation.BUNYAN;\n }\n\n let featureBitMap = StatsbeatFeature.NONE;\n featureBitMap |= StatsbeatFeature.DISTRO;\n\n if (statsbeatOptions.browserSdkLoader === true) {\n featureBitMap |= StatsbeatFeature.BROWSER_SDK_LOADER;\n }\n // Determines if the customer has activated the Live Metrics feature\n if (statsbeatOptions.liveMetrics === true) {\n featureBitMap |= StatsbeatFeature.LIVE_METRICS;\n }\n\n try {\n const currentFeaturesBitMap = Number(process.env[AZURE_MONITOR_STATSBEAT_FEATURES]);\n if (!isNaN(currentFeaturesBitMap)) {\n featureBitMap |= currentFeaturesBitMap;\n }\n process.env[AZURE_MONITOR_STATSBEAT_FEATURES] = JSON.stringify({\n instrumentation: instrumentationBitMap,\n feature: featureBitMap,\n });\n } catch (error) {\n InternalLogger.getInstance().error(\"Failed call to JSON.stringify.\", error);\n }\n };\n}\n\n/**\n * Singleton Statsbeat instance.\n * @internal\n */\nexport function getInstance(): StatsbeatConfiguration {\n if (!instance) {\n instance = new StatsbeatConfiguration();\n }\n return instance;\n}\n"]}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@azure/monitor-opentelemetry",
3
3
  "author": "Microsoft Corporation",
4
4
  "sdk-type": "client",
5
- "version": "1.3.0",
5
+ "version": "1.4.0",
6
6
  "description": "Azure Monitor OpenTelemetry (Node.js)",
7
7
  "main": "dist/index.js",
8
8
  "module": "dist-esm/src/index.js",
@@ -26,7 +26,6 @@
26
26
  "test:browser": "npm run unit-test:browser",
27
27
  "unit-test:browser": "echo skipped",
28
28
  "unit-test:node": "dev-tool run test:node-tsx-ts --no-test-proxy=true -- --timeout 1200000 \"test/internal/unit/**/*.test.ts\"",
29
- "unit-test:node:debug": "dev-tool run test:node-js-input --no-test-proxy=true -- --inspect-brk --timeout 1200000 \"test/internal/unit/**/*.test.ts\"",
30
29
  "unit-test": "npm run unit-test:node && npm run unit-test:browser",
31
30
  "integration-test:browser": "echo skipped",
32
31
  "integration-test:node": "dev-tool run test:node-ts-input --no-test-proxy=true -- \"test/internal/functional/**/*.test.ts\"",
@@ -70,17 +69,17 @@
70
69
  "@types/mocha": "^10.0.0",
71
70
  "@types/node": "^18.0.0",
72
71
  "@types/sinon": "^17.0.0",
73
- "c8": "^8.0.0",
72
+ "c8": "^9.1.0",
74
73
  "cross-env": "^7.0.2",
75
74
  "dotenv": "^16.0.0",
76
75
  "eslint": "^8.0.0",
77
76
  "eslint-plugin-node": "^11.1.0",
78
77
  "mocha": "^10.0.0",
79
- "nock": "^12.0.3",
78
+ "nock": "^13.5.4",
80
79
  "rimraf": "^5.0.5",
81
80
  "sinon": "^17.0.0",
82
81
  "tsx": "^4.7.1",
83
- "typescript": "~5.3.3"
82
+ "typescript": "~5.4.5"
84
83
  },
85
84
  "dependencies": {
86
85
  "@azure/core-client": "^1.0.0",
@@ -88,28 +87,28 @@
88
87
  "@azure/core-rest-pipeline": "^1.1.0",
89
88
  "@azure/functions": "^3.2.0",
90
89
  "@azure/logger": "^1.0.0",
91
- "@azure/monitor-opentelemetry-exporter": "1.0.0-beta.21",
90
+ "@azure/monitor-opentelemetry-exporter": "1.0.0-beta.22",
92
91
  "@azure/opentelemetry-instrumentation-azure-sdk": "^1.0.0-beta.5",
93
92
  "@microsoft/applicationinsights-web-snippet": "^1.1.2",
94
93
  "@opentelemetry/api": "^1.8.0",
95
- "@opentelemetry/api-logs": "^0.49.1",
96
- "@opentelemetry/core": "^1.22.0",
97
- "@opentelemetry/instrumentation": "^0.49.1",
98
- "@opentelemetry/instrumentation-bunyan": "^0.36.0",
99
- "@opentelemetry/instrumentation-http": "^0.49.1",
100
- "@opentelemetry/instrumentation-mongodb": "^0.40.0",
101
- "@opentelemetry/instrumentation-mysql": "^0.36.0",
102
- "@opentelemetry/instrumentation-pg": "^0.39.0",
103
- "@opentelemetry/instrumentation-redis": "^0.37.0",
104
- "@opentelemetry/instrumentation-redis-4": "^0.37.0",
105
- "@opentelemetry/resource-detector-azure": "^0.2.4",
106
- "@opentelemetry/resources": "^1.22.0",
107
- "@opentelemetry/sdk-logs": "^0.49.1",
108
- "@opentelemetry/sdk-metrics": "^1.22.0",
109
- "@opentelemetry/sdk-node": "^0.49.1",
110
- "@opentelemetry/sdk-trace-base": "^1.22.0",
111
- "@opentelemetry/sdk-trace-node": "^1.22.0",
112
- "@opentelemetry/semantic-conventions": "^1.22.0",
94
+ "@opentelemetry/api-logs": "^0.50.0",
95
+ "@opentelemetry/core": "^1.23.0",
96
+ "@opentelemetry/instrumentation": "^0.50.0",
97
+ "@opentelemetry/instrumentation-bunyan": "^0.37.0",
98
+ "@opentelemetry/instrumentation-http": "^0.50.0",
99
+ "@opentelemetry/instrumentation-mongodb": "^0.42.0",
100
+ "@opentelemetry/instrumentation-mysql": "^0.37.0",
101
+ "@opentelemetry/instrumentation-pg": "^0.40.0",
102
+ "@opentelemetry/instrumentation-redis": "^0.38.0",
103
+ "@opentelemetry/instrumentation-redis-4": "^0.38.0",
104
+ "@opentelemetry/resource-detector-azure": "^0.2.6",
105
+ "@opentelemetry/resources": "^1.23.0",
106
+ "@opentelemetry/sdk-logs": "^0.50.0",
107
+ "@opentelemetry/sdk-metrics": "^1.23.0",
108
+ "@opentelemetry/sdk-node": "^0.50.0",
109
+ "@opentelemetry/sdk-trace-base": "^1.23.0",
110
+ "@opentelemetry/sdk-trace-node": "^1.23.0",
111
+ "@opentelemetry/semantic-conventions": "^1.23.0",
113
112
  "tslib": "^2.6.2"
114
113
  },
115
114
  "sideEffects": false,
@@ -14,10 +14,12 @@ export declare interface AzureMonitorOpenTelemetryOptions {
14
14
  resource?: Resource;
15
15
  /** The rate of telemetry items tracked that should be transmitted (Default 1.0) */
16
16
  samplingRatio?: number;
17
- /** Enable Live Metrics feature */
17
+ /** Enable Live Metrics feature (Default false)*/
18
18
  enableLiveMetrics?: boolean;
19
- /** Enable Standard Metrics feature */
19
+ /** Enable Standard Metrics feature (Default true)*/
20
20
  enableStandardMetrics?: boolean;
21
+ /** Enable log sampling based on trace (Default true) */
22
+ enableTraceBasedSamplingForLogs?: boolean;
21
23
  /** OpenTelemetry Instrumentations options included as part of Azure Monitor (azureSdk, http, mongoDb, mySql, postgreSql, redis, redis4) */
22
24
  instrumentationOptions?: InstrumentationOptions;
23
25
  /** Application Insights Web Instrumentation options (enabled, connectionString, src, config)*/