@azure/monitor-opentelemetry-exporter 1.0.0-beta.10 → 1.0.0-beta.12

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.
Files changed (29) hide show
  1. package/README.md +6 -6
  2. package/dist/index.js +286 -188
  3. package/dist-esm/src/export/base.js +22 -16
  4. package/dist-esm/src/export/base.js.map +1 -1
  5. package/dist-esm/src/export/statsbeat/longIntervalStatsbeatMetrics.js +118 -0
  6. package/dist-esm/src/export/statsbeat/longIntervalStatsbeatMetrics.js.map +1 -0
  7. package/dist-esm/src/export/statsbeat/networkStatsbeatMetrics.js +249 -0
  8. package/dist-esm/src/export/statsbeat/networkStatsbeatMetrics.js.map +1 -0
  9. package/dist-esm/src/export/{statsbeat.js → statsbeat/statsbeatExporter.js} +4 -5
  10. package/dist-esm/src/export/statsbeat/statsbeatExporter.js.map +1 -0
  11. package/dist-esm/src/export/statsbeat/statsbeatMetrics.js +26 -240
  12. package/dist-esm/src/export/statsbeat/statsbeatMetrics.js.map +1 -1
  13. package/dist-esm/src/export/statsbeat/types.js +9 -0
  14. package/dist-esm/src/export/statsbeat/types.js.map +1 -1
  15. package/dist-esm/src/generated/applicationInsightsClient.js +1 -1
  16. package/dist-esm/src/generated/applicationInsightsClient.js.map +1 -1
  17. package/dist-esm/src/index.js +1 -1
  18. package/dist-esm/src/index.js.map +1 -1
  19. package/dist-esm/src/platform/nodejs/context/context.js +9 -2
  20. package/dist-esm/src/platform/nodejs/context/context.js.map +1 -1
  21. package/dist-esm/src/utils/constants/applicationinsights.js +1 -30
  22. package/dist-esm/src/utils/constants/applicationinsights.js.map +1 -1
  23. package/dist-esm/src/utils/metricUtils.js +2 -42
  24. package/dist-esm/src/utils/metricUtils.js.map +1 -1
  25. package/dist-esm/src/utils/spanUtils.js +35 -31
  26. package/dist-esm/src/utils/spanUtils.js.map +1 -1
  27. package/package.json +13 -14
  28. package/types/monitor-opentelemetry-exporter.d.ts +28 -2
  29. package/dist-esm/src/export/statsbeat.js.map +0 -1
package/dist/index.js CHANGED
@@ -5,8 +5,8 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
6
6
  var api = require('@opentelemetry/api');
7
7
  var core = require('@opentelemetry/core');
8
- var coreRestPipeline = require('@azure/core-rest-pipeline');
9
8
  var sdkMetrics = require('@opentelemetry/sdk-metrics');
9
+ var coreRestPipeline = require('@azure/core-rest-pipeline');
10
10
  var os$1 = require('os');
11
11
  var semanticConventions = require('@opentelemetry/semantic-conventions');
12
12
  var url = require('url');
@@ -66,7 +66,7 @@ const TIME_SINCE_ENQUEUED = "timeSinceEnqueued";
66
66
  * AzureMonitorTraceExporter version.
67
67
  * @internal
68
68
  */
69
- const packageVersion = "1.0.0-beta.10";
69
+ const packageVersion = "1.0.0-beta.12";
70
70
  var DependencyTypes;
71
71
  (function (DependencyTypes) {
72
72
  DependencyTypes["InProc"] = "InProc";
@@ -76,35 +76,6 @@ var DependencyTypes;
76
76
  DependencyTypes["Grpc"] = "GRPC";
77
77
  })(DependencyTypes || (DependencyTypes = {}));
78
78
  const AzureMonitorSampleRate = "_MS.sampleRate";
79
- var StandardMetrics;
80
- (function (StandardMetrics) {
81
- StandardMetrics["HTTP_REQUEST_DURATION"] = "azureMonitor.http.requestDuration";
82
- StandardMetrics["HTTP_DEPENDENCY_DURATION"] = "azureMonitor.http.dependencyDuration";
83
- StandardMetrics["EXCEPTION_COUNT"] = "azureMonitor.exceptionCount";
84
- StandardMetrics["TRACE_COUNT"] = "azureMonitor.traceCount";
85
- })(StandardMetrics || (StandardMetrics = {}));
86
- var StandardMetricIds;
87
- (function (StandardMetricIds) {
88
- StandardMetricIds["REQUEST_DURATION"] = "requests/duration";
89
- StandardMetricIds["DEPENDENCY_DURATION"] = "dependencies/duration";
90
- StandardMetricIds["EXCEPTION_COUNT"] = "exceptions/count";
91
- StandardMetricIds["TRACE_COUNT"] = "traces/count";
92
- })(StandardMetricIds || (StandardMetricIds = {}));
93
- // Names expected in Breeze side for dimensions
94
- const PreAggregatedMetricPropertyNames = {
95
- cloudRoleInstance: "cloud/roleInstance",
96
- cloudRoleName: "cloud/roleName",
97
- operationSynthetic: "operation/synthetic",
98
- requestSuccess: "Request.Success",
99
- requestResultCode: "request/resultCode",
100
- dependencyType: "Dependency.Type",
101
- dependencyTarget: "dependency/target",
102
- dependencySuccess: "Dependency.Success",
103
- dependencyResultCode: "dependency/resultCode",
104
- traceSeverityLevel: "trace/severityLevel",
105
- metricId: "_MS.MetricId",
106
- IsAutocollected: "_MS.IsAutocollected",
107
- };
108
79
 
109
80
  /**
110
81
  * ApplicationInsightsSampler is responsible for the following:
@@ -1756,7 +1727,7 @@ class ApplicationInsightsClient extends coreClient__namespace.ServiceClient {
1756
1727
  const defaults = {
1757
1728
  requestContentType: "application/json; charset=utf-8"
1758
1729
  };
1759
- const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.9`;
1730
+ const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.12`;
1760
1731
  const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
1761
1732
  ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
1762
1733
  : `${packageDetails}`;
@@ -1893,7 +1864,7 @@ class HttpSender {
1893
1864
  }
1894
1865
 
1895
1866
  // Copyright (c) Microsoft Corporation.
1896
- let instance = null;
1867
+ let instance$1 = null;
1897
1868
  /**
1898
1869
  * Azure Telemetry context.
1899
1870
  * @internal
@@ -1912,21 +1883,28 @@ class Context {
1912
1883
  [Context.nodeVersion] = node.split(".");
1913
1884
  Context.opentelemetryVersion = core.SDK_INFO[semanticConventions.SemanticResourceAttributes.TELEMETRY_SDK_VERSION];
1914
1885
  Context.sdkVersion = packageVersion;
1915
- this.tags[KnownContextTagKeys.AiInternalSdkVersion] = `node${Context.nodeVersion}:otel${Context.opentelemetryVersion}:ext${Context.sdkVersion}`;
1886
+ let prefix = process.env["AZURE_MONITOR_AGENT_PREFIX"]
1887
+ ? process.env["AZURE_MONITOR_AGENT_PREFIX"]
1888
+ : "";
1889
+ let version = process.env["AZURE_MONITOR_DISTRO_VERSION"]
1890
+ ? `dst${process.env["AZURE_MONITOR_DISTRO_VERSION"]}`
1891
+ : `ext${Context.sdkVersion}`;
1892
+ let internalSdkVersion = `${prefix}node${Context.nodeVersion}:otel${Context.opentelemetryVersion}:${version}`;
1893
+ this.tags[KnownContextTagKeys.AiInternalSdkVersion] = internalSdkVersion;
1916
1894
  }
1917
1895
  }
1918
1896
  Context.sdkVersion = null;
1919
1897
  Context.opentelemetryVersion = null;
1920
1898
  Context.nodeVersion = "";
1921
1899
  /**
1922
- * Singleton Context instance.
1900
+ * Singleton Context instance
1923
1901
  * @internal
1924
1902
  */
1925
- function getInstance() {
1926
- if (!instance) {
1927
- instance = new Context();
1903
+ function getInstance$1() {
1904
+ if (!instance$1) {
1905
+ instance$1 = new Context();
1928
1906
  }
1929
- return instance;
1907
+ return instance$1;
1930
1908
  }
1931
1909
 
1932
1910
  // Copyright (c) Microsoft Corporation.
@@ -2001,6 +1979,8 @@ var StatsbeatCounter;
2001
1979
  StatsbeatCounter["THROTTLE_COUNT"] = "Throttle Count";
2002
1980
  StatsbeatCounter["EXCEPTION_COUNT"] = "Exception Count";
2003
1981
  StatsbeatCounter["AVERAGE_DURATION"] = "Request Duration";
1982
+ StatsbeatCounter["ATTACH"] = "Attach";
1983
+ StatsbeatCounter["FEATURE"] = "Feature";
2004
1984
  })(StatsbeatCounter || (StatsbeatCounter = {}));
2005
1985
  const AIMS_URI = "http://169.254.169.254/metadata/instance/compute";
2006
1986
  const AIMS_API_VERSION = "api-version=2017-12-01";
@@ -2018,60 +1998,23 @@ const EU_ENDPOINTS = [
2018
1998
  "swedencentral",
2019
1999
  "switzerlandnorth",
2020
2000
  "switzerlandwest",
2001
+ "uksouth",
2002
+ "ukwest",
2021
2003
  ];
2004
+ var StatsbeatFeatureType;
2005
+ (function (StatsbeatFeatureType) {
2006
+ StatsbeatFeatureType["FEATURE"] = "Feature";
2007
+ StatsbeatFeatureType["INSTRUMENTATION"] = "Instrumentation";
2008
+ })(StatsbeatFeatureType || (StatsbeatFeatureType = {}));
2022
2009
 
2023
2010
  // Copyright (c) Microsoft Corporation.
2024
2011
  const os = require("os");
2025
2012
  class StatsbeatMetrics {
2026
- constructor(options) {
2027
- this._isInitialized = false;
2028
- this._networkStatsbeatCollection = [];
2029
- this._statsCollectionShortInterval = 900000; // 15 minutes
2030
- // Custom dimensions
2013
+ constructor() {
2031
2014
  this._resourceProvider = StatsbeatResourceProvider.unknown;
2015
+ this._vmInfo = {};
2032
2016
  this._os = os.type();
2033
- this._attach = "sdk";
2034
- this._connectionString = this._getConnectionString(options.endpointUrl);
2035
- this._meterProvider = new sdkMetrics.MeterProvider();
2036
- const exporterConfig = {
2037
- connectionString: this._connectionString,
2038
- };
2039
- this._azureExporter = new _AzureMonitorStatsbeatExporter(exporterConfig);
2040
- const metricReaderOptions = {
2041
- exporter: this._azureExporter,
2042
- exportIntervalMillis: options.collectionInterval || this._statsCollectionShortInterval, // 15 minutes
2043
- };
2044
- // Exports Network Statsbeat every 15 minutes
2045
- this._metricReader = new sdkMetrics.PeriodicExportingMetricReader(metricReaderOptions);
2046
- this._meterProvider.addMetricReader(this._metricReader);
2047
- this._meter = this._meterProvider.getMeter("Azure Monitor NetworkStatsbeat");
2048
- this._endpointUrl = options.endpointUrl;
2049
- this._runtimeVersion = process.version;
2050
- this._language = STATSBEAT_LANGUAGE;
2051
- this._version = packageVersion;
2052
- this._host = this._getShortHost(options.endpointUrl);
2053
- this._cikey = options.instrumentationKey;
2054
- this._successCountGauge = this._meter.createObservableGauge(StatsbeatCounter.SUCCESS_COUNT);
2055
- this._failureCountGauge = this._meter.createObservableGauge(StatsbeatCounter.FAILURE_COUNT);
2056
- this._retryCountGauge = this._meter.createObservableGauge(StatsbeatCounter.RETRY_COUNT);
2057
- this._throttleCountGauge = this._meter.createObservableGauge(StatsbeatCounter.THROTTLE_COUNT);
2058
- this._exceptionCountGauge = this._meter.createObservableGauge(StatsbeatCounter.EXCEPTION_COUNT);
2059
- this._averageDurationGauge = this._meter.createObservableGauge(StatsbeatCounter.AVERAGE_DURATION);
2060
- this._commonProperties = {
2061
- os: this._os,
2062
- rp: this._resourceProvider,
2063
- cikey: this._cikey,
2064
- runtimeVersion: this._runtimeVersion,
2065
- language: this._language,
2066
- version: this._version,
2067
- attach: this._attach,
2068
- };
2069
- this._networkProperties = {
2070
- endpoint: this._endpointUrl,
2071
- host: this._host,
2072
- };
2073
- this._isInitialized = true;
2074
- this._initialize();
2017
+ this._resourceIdentifier = "";
2075
2018
  }
2076
2019
  async _getResourceProvider() {
2077
2020
  // Check resource provider
@@ -2086,6 +2029,11 @@ class StatsbeatMetrics {
2086
2029
  }
2087
2030
  else if (await this.getAzureComputeMetadata()) {
2088
2031
  this._resourceProvider = StatsbeatResourceProvider.vm;
2032
+ this._resourceIdentifier = this._vmInfo.id + "/" + this._vmInfo.subscriptionId;
2033
+ // Overrride OS as VM info have higher precedence
2034
+ if (this._vmInfo.osType) {
2035
+ this._os = this._vmInfo.osType;
2036
+ }
2089
2037
  }
2090
2038
  else {
2091
2039
  this._resourceProvider = StatsbeatResourceProvider.unknown;
@@ -2105,6 +2053,23 @@ class StatsbeatMetrics {
2105
2053
  .sendRequest(request)
2106
2054
  .then((res) => {
2107
2055
  if (res.status === 200) {
2056
+ // Success; VM
2057
+ this._vmInfo.isVM = true;
2058
+ let virtualMachineData = "";
2059
+ res.on("data", (data) => {
2060
+ virtualMachineData += data;
2061
+ });
2062
+ res.on("end", () => {
2063
+ try {
2064
+ let data = JSON.parse(virtualMachineData);
2065
+ this._vmInfo.id = data["vmId"] || "";
2066
+ this._vmInfo.subscriptionId = data["subscriptionId"] || "";
2067
+ this._vmInfo.osType = data["osType"] || "";
2068
+ }
2069
+ catch (error) {
2070
+ api.diag.debug("Failed to parse JSON: ", error);
2071
+ }
2072
+ });
2108
2073
  return true;
2109
2074
  }
2110
2075
  else {
@@ -2116,27 +2081,88 @@ class StatsbeatMetrics {
2116
2081
  });
2117
2082
  return false;
2118
2083
  }
2084
+ _getConnectionString(endpointUrl) {
2085
+ let currentEndpoint = endpointUrl;
2086
+ for (let i = 0; i < EU_ENDPOINTS.length; i++) {
2087
+ if (currentEndpoint.includes(EU_ENDPOINTS[i])) {
2088
+ return EU_CONNECTION_STRING;
2089
+ }
2090
+ }
2091
+ return NON_EU_CONNECTION_STRING;
2092
+ }
2093
+ }
2094
+
2095
+ // Copyright (c) Microsoft Corporation.
2096
+ class NetworkStatsbeatMetrics extends StatsbeatMetrics {
2097
+ constructor(options) {
2098
+ super();
2099
+ this._isInitialized = false;
2100
+ this._statsCollectionShortInterval = 900000; // 15 minutes
2101
+ this._networkStatsbeatCollection = [];
2102
+ this._attach = "sdk";
2103
+ this._connectionString = super._getConnectionString(options.endpointUrl);
2104
+ this._networkStatsbeatMeterProvider = new sdkMetrics.MeterProvider();
2105
+ const exporterConfig = {
2106
+ connectionString: this._connectionString,
2107
+ };
2108
+ this._networkAzureExporter = new AzureMonitorStatsbeatExporter(exporterConfig);
2109
+ // Exports Network Statsbeat every 15 minutes
2110
+ const networkMetricReaderOptions = {
2111
+ exporter: this._networkAzureExporter,
2112
+ exportIntervalMillis: options.networkCollectionInterval || this._statsCollectionShortInterval, // 15 minutes
2113
+ };
2114
+ this._networkMetricReader = new sdkMetrics.PeriodicExportingMetricReader(networkMetricReaderOptions);
2115
+ this._networkStatsbeatMeterProvider.addMetricReader(this._networkMetricReader);
2116
+ this._networkStatsbeatMeter = this._networkStatsbeatMeterProvider.getMeter("Azure Monitor Network Statsbeat");
2117
+ this._endpointUrl = options.endpointUrl;
2118
+ this._runtimeVersion = process.version;
2119
+ this._language = STATSBEAT_LANGUAGE;
2120
+ this._version = packageVersion;
2121
+ this._host = this._getShortHost(options.endpointUrl);
2122
+ this._cikey = options.instrumentationKey;
2123
+ this._successCountGauge = this._networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.SUCCESS_COUNT);
2124
+ this._failureCountGauge = this._networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.FAILURE_COUNT);
2125
+ this._retryCountGauge = this._networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.RETRY_COUNT);
2126
+ this._throttleCountGauge = this._networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.THROTTLE_COUNT);
2127
+ this._exceptionCountGauge = this._networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.EXCEPTION_COUNT);
2128
+ this._averageDurationGauge = this._networkStatsbeatMeter.createObservableGauge(StatsbeatCounter.AVERAGE_DURATION);
2129
+ this._commonProperties = {
2130
+ os: super._os,
2131
+ rp: super._resourceProvider,
2132
+ cikey: this._cikey,
2133
+ runtimeVersion: this._runtimeVersion,
2134
+ language: this._language,
2135
+ version: this._version,
2136
+ attach: this._attach,
2137
+ };
2138
+ this._networkProperties = {
2139
+ endpoint: this._endpointUrl,
2140
+ host: this._host,
2141
+ };
2142
+ this._isInitialized = true;
2143
+ this._initialize();
2144
+ }
2119
2145
  isInitialized() {
2120
2146
  return this._isInitialized;
2121
2147
  }
2122
2148
  shutdown() {
2123
- this._meterProvider.shutdown();
2149
+ this._networkStatsbeatMeterProvider.shutdown();
2124
2150
  }
2125
2151
  async _initialize() {
2126
2152
  try {
2127
- await this._getResourceProvider();
2128
- // Add observable callbacks
2153
+ await super._getResourceProvider();
2154
+ // Add network observable callbacks
2129
2155
  this._successCountGauge.addCallback(this._successCallback.bind(this));
2130
- this._meter.addBatchObservableCallback(this._failureCallback.bind(this), [
2156
+ this._networkStatsbeatMeter.addBatchObservableCallback(this._failureCallback.bind(this), [
2131
2157
  this._failureCountGauge,
2132
2158
  ]);
2133
- this._meter.addBatchObservableCallback(this._retryCallback.bind(this), [
2159
+ this._networkStatsbeatMeter.addBatchObservableCallback(this._retryCallback.bind(this), [
2134
2160
  this._retryCountGauge,
2135
2161
  ]);
2136
- this._meter.addBatchObservableCallback(this._throttleCallback.bind(this), [
2162
+ this._networkStatsbeatMeter.addBatchObservableCallback(this._throttleCallback.bind(this), [
2137
2163
  this._throttleCountGauge,
2138
2164
  ]);
2139
- this._meter.addBatchObservableCallback(this._exceptionCallback.bind(this), [
2165
+ this._networkStatsbeatMeter.addBatchObservableCallback(this._exceptionCallback.bind(this), [
2140
2166
  this._exceptionCountGauge,
2141
2167
  ]);
2142
2168
  this._averageDurationGauge.addCallback(this._durationCallback.bind(this));
@@ -2299,21 +2325,123 @@ class StatsbeatMetrics {
2299
2325
  if (res != null && res.length > 1) {
2300
2326
  shortHost = res[1];
2301
2327
  }
2328
+ shortHost = shortHost.replace(".in.applicationinsights.azure.com", "");
2302
2329
  }
2303
2330
  catch (error) {
2304
2331
  api.diag.debug("Failed to get the short host name.");
2305
2332
  }
2306
2333
  return shortHost;
2307
2334
  }
2308
- _getConnectionString(endpointUrl) {
2309
- let currentEndpoint = endpointUrl;
2310
- for (let i = 0; i < EU_ENDPOINTS.length; i++) {
2311
- if (currentEndpoint.includes(EU_ENDPOINTS[i])) {
2312
- return EU_CONNECTION_STRING;
2335
+ }
2336
+
2337
+ // Copyright (c) Microsoft Corporation.
2338
+ let instance = null;
2339
+ /**
2340
+ * Long Interval Statsbeat Metrics
2341
+ * @internal
2342
+ */
2343
+ class LongIntervalStatsbeatMetrics extends StatsbeatMetrics {
2344
+ constructor(options) {
2345
+ super();
2346
+ this._AZURE_MONITOR_STATSBEAT_FEATURES = process.env.AZURE_MONITOR_STATSBEAT_FEATURES;
2347
+ this._statsCollectionLongInterval = 86400000; // 1 day
2348
+ this._isInitialized = false;
2349
+ this._attach = "sdk";
2350
+ this._feature = 0;
2351
+ this._instrumentation = 0;
2352
+ this._connectionString = super._getConnectionString(options.endpointUrl);
2353
+ const exporterConfig = {
2354
+ connectionString: this._connectionString,
2355
+ };
2356
+ if (this._AZURE_MONITOR_STATSBEAT_FEATURES) {
2357
+ try {
2358
+ this._feature = JSON.parse(this._AZURE_MONITOR_STATSBEAT_FEATURES).feature;
2359
+ this._instrumentation = JSON.parse(this._AZURE_MONITOR_STATSBEAT_FEATURES).instrumentation;
2360
+ }
2361
+ catch (error) {
2362
+ api.diag.error(`LongIntervalStatsbeat: Failed to parse features/instrumentations (error ${error})`);
2313
2363
  }
2314
2364
  }
2315
- return NON_EU_CONNECTION_STRING;
2365
+ this._longIntervalStatsbeatMeterProvider = new sdkMetrics.MeterProvider();
2366
+ this._longIntervalAzureExporter = new AzureMonitorStatsbeatExporter(exporterConfig);
2367
+ // Export Long Interval Statsbeats every day
2368
+ const longIntervalMetricReaderOptions = {
2369
+ exporter: this._longIntervalAzureExporter,
2370
+ exportIntervalMillis: Number(process.env.LONG_INTERVAL_EXPORT_MILLIS) || this._statsCollectionLongInterval, // 1 day
2371
+ };
2372
+ this._longIntervalMetricReader = new sdkMetrics.PeriodicExportingMetricReader(longIntervalMetricReaderOptions);
2373
+ this._longIntervalStatsbeatMeterProvider.addMetricReader(this._longIntervalMetricReader);
2374
+ this._longIntervalStatsbeatMeter = this._longIntervalStatsbeatMeterProvider.getMeter("Azure Monitor Long Interval Statsbeat");
2375
+ // Assign Common Properties
2376
+ this._runtimeVersion = process.version;
2377
+ this._language = STATSBEAT_LANGUAGE;
2378
+ this._version = packageVersion;
2379
+ this._cikey = options.instrumentationKey;
2380
+ this._featureStatsbeatGauge = this._longIntervalStatsbeatMeter.createObservableGauge(StatsbeatCounter.FEATURE);
2381
+ this._attachStatsbeatGauge = this._longIntervalStatsbeatMeter.createObservableGauge(StatsbeatCounter.ATTACH);
2382
+ this._commonProperties = {
2383
+ os: super._os,
2384
+ rp: super._resourceProvider,
2385
+ cikey: this._cikey,
2386
+ runtimeVersion: this._runtimeVersion,
2387
+ language: this._language,
2388
+ version: this._version,
2389
+ attach: this._attach,
2390
+ };
2391
+ this._attachProperties = {
2392
+ rpId: super._resourceIdentifier,
2393
+ };
2394
+ this._isInitialized = true;
2395
+ this._initialize();
2316
2396
  }
2397
+ async _initialize() {
2398
+ try {
2399
+ await this._getResourceProvider();
2400
+ // Add long interval observable callbacks
2401
+ this._attachStatsbeatGauge.addCallback(this._attachCallback.bind(this));
2402
+ this._longIntervalStatsbeatMeter.addBatchObservableCallback(this._featureCallback.bind(this), [this._featureStatsbeatGauge]);
2403
+ // Export Feature/Attach Statsbeat once upon app initialization
2404
+ this._longIntervalAzureExporter.export((await this._longIntervalMetricReader.collect()).resourceMetrics, (result) => {
2405
+ if (result.code !== core.ExportResultCode.SUCCESS) {
2406
+ api.diag.error(`LongIntervalStatsbeat: metrics export failed (error ${result.error})`);
2407
+ }
2408
+ });
2409
+ }
2410
+ catch (error) {
2411
+ api.diag.debug("Call to get the resource provider failed.");
2412
+ }
2413
+ }
2414
+ _featureCallback(observableResult) {
2415
+ let attributes;
2416
+ if (this._instrumentation) {
2417
+ attributes = Object.assign(Object.assign({}, this._commonProperties), { feature: this._instrumentation, type: StatsbeatFeatureType.INSTRUMENTATION });
2418
+ observableResult.observe(this._featureStatsbeatGauge, 1, Object.assign({}, attributes));
2419
+ }
2420
+ if (this._feature) {
2421
+ attributes = Object.assign(Object.assign({}, this._commonProperties), { feature: this._feature, type: StatsbeatFeatureType.FEATURE });
2422
+ observableResult.observe(this._featureStatsbeatGauge, 1, Object.assign({}, attributes));
2423
+ }
2424
+ }
2425
+ _attachCallback(observableResult) {
2426
+ let attributes = Object.assign(Object.assign({}, this._commonProperties), this._attachProperties);
2427
+ observableResult.observe(1, attributes);
2428
+ }
2429
+ isInitialized() {
2430
+ return this._isInitialized;
2431
+ }
2432
+ shutdown() {
2433
+ this._longIntervalStatsbeatMeterProvider.shutdown();
2434
+ }
2435
+ }
2436
+ /**
2437
+ * Singleton LongIntervalStatsbeatMetrics instance.
2438
+ * @internal
2439
+ */
2440
+ function getInstance(options) {
2441
+ if (!instance) {
2442
+ instance = new LongIntervalStatsbeatMetrics(options);
2443
+ }
2444
+ return instance;
2317
2445
  }
2318
2446
 
2319
2447
  // Copyright (c) Microsoft Corporation.
@@ -2357,7 +2485,11 @@ class AzureMonitorBaseExporter {
2357
2485
  this._persister = new FileSystemPersist(this._instrumentationKey, this._options);
2358
2486
  if (!this._isStatsbeatExporter) {
2359
2487
  // Initialize statsbeatMetrics
2360
- this._statsbeatMetrics = new StatsbeatMetrics({
2488
+ this._networkStatsbeatMetrics = new NetworkStatsbeatMetrics({
2489
+ instrumentationKey: this._instrumentationKey,
2490
+ endpointUrl: this._endpointUrl,
2491
+ });
2492
+ this._longIntervalStatsbeatMetrics = getInstance({
2361
2493
  instrumentationKey: this._instrumentationKey,
2362
2494
  endpointUrl: this._endpointUrl,
2363
2495
  });
@@ -2413,13 +2545,13 @@ class AzureMonitorBaseExporter {
2413
2545
  this._retryTimer.unref();
2414
2546
  }
2415
2547
  // If we are not exportings statsbeat and statsbeat is not disabled -- count success
2416
- (_a = this._statsbeatMetrics) === null || _a === void 0 ? void 0 : _a.countSuccess(duration);
2548
+ (_a = this._networkStatsbeatMetrics) === null || _a === void 0 ? void 0 : _a.countSuccess(duration);
2417
2549
  return { code: core.ExportResultCode.SUCCESS };
2418
2550
  }
2419
2551
  else if (statusCode && isRetriable(statusCode)) {
2420
2552
  // Failed -- persist failed data
2421
2553
  if (statusCode === 429 || statusCode === 439) {
2422
- (_b = this._statsbeatMetrics) === null || _b === void 0 ? void 0 : _b.countThrottle(statusCode);
2554
+ (_b = this._networkStatsbeatMetrics) === null || _b === void 0 ? void 0 : _b.countThrottle(statusCode);
2423
2555
  }
2424
2556
  if (result) {
2425
2557
  api.diag.info(result);
@@ -2433,27 +2565,27 @@ class AzureMonitorBaseExporter {
2433
2565
  });
2434
2566
  }
2435
2567
  if (filteredEnvelopes.length > 0) {
2436
- (_c = this._statsbeatMetrics) === null || _c === void 0 ? void 0 : _c.countRetry(statusCode);
2568
+ (_c = this._networkStatsbeatMetrics) === null || _c === void 0 ? void 0 : _c.countRetry(statusCode);
2437
2569
  // calls resultCallback(ExportResult) based on result of persister.push
2438
2570
  return await this._persist(filteredEnvelopes);
2439
2571
  }
2440
2572
  // Failed -- not retriable
2441
- (_d = this._statsbeatMetrics) === null || _d === void 0 ? void 0 : _d.countFailure(duration, statusCode);
2573
+ (_d = this._networkStatsbeatMetrics) === null || _d === void 0 ? void 0 : _d.countFailure(duration, statusCode);
2442
2574
  return {
2443
2575
  code: core.ExportResultCode.FAILED,
2444
2576
  };
2445
2577
  }
2446
2578
  else {
2447
2579
  // calls resultCallback(ExportResult) based on result of persister.push
2448
- (_e = this._statsbeatMetrics) === null || _e === void 0 ? void 0 : _e.countRetry(statusCode);
2580
+ (_e = this._networkStatsbeatMetrics) === null || _e === void 0 ? void 0 : _e.countRetry(statusCode);
2449
2581
  return await this._persist(envelopes);
2450
2582
  }
2451
2583
  }
2452
2584
  else {
2453
2585
  // Failed -- not retriable
2454
- if (this._statsbeatMetrics) {
2586
+ if (this._networkStatsbeatMetrics) {
2455
2587
  if (statusCode) {
2456
- this._statsbeatMetrics.countFailure(duration, statusCode);
2588
+ this._networkStatsbeatMetrics.countFailure(duration, statusCode);
2457
2589
  }
2458
2590
  }
2459
2591
  else {
@@ -2485,34 +2617,35 @@ class AzureMonitorBaseExporter {
2485
2617
  }
2486
2618
  else {
2487
2619
  let redirectError = new Error("Circular redirect");
2488
- (_f = this._statsbeatMetrics) === null || _f === void 0 ? void 0 : _f.countException(redirectError);
2620
+ (_f = this._networkStatsbeatMetrics) === null || _f === void 0 ? void 0 : _f.countException(redirectError);
2489
2621
  return { code: core.ExportResultCode.FAILED, error: redirectError };
2490
2622
  }
2491
2623
  }
2492
2624
  else if (restError.statusCode && isRetriable(restError.statusCode)) {
2493
- (_g = this._statsbeatMetrics) === null || _g === void 0 ? void 0 : _g.countRetry(restError.statusCode);
2625
+ (_g = this._networkStatsbeatMetrics) === null || _g === void 0 ? void 0 : _g.countRetry(restError.statusCode);
2494
2626
  return await this._persist(envelopes);
2495
2627
  }
2496
2628
  if (this._isNetworkError(restError)) {
2497
2629
  if (restError.statusCode) {
2498
- (_h = this._statsbeatMetrics) === null || _h === void 0 ? void 0 : _h.countRetry(restError.statusCode);
2630
+ (_h = this._networkStatsbeatMetrics) === null || _h === void 0 ? void 0 : _h.countRetry(restError.statusCode);
2499
2631
  }
2500
2632
  api.diag.error("Retrying due to transient client side error. Error message:", restError.message);
2501
2633
  return await this._persist(envelopes);
2502
2634
  }
2503
- (_j = this._statsbeatMetrics) === null || _j === void 0 ? void 0 : _j.countException(restError);
2635
+ (_j = this._networkStatsbeatMetrics) === null || _j === void 0 ? void 0 : _j.countException(restError);
2504
2636
  api.diag.error("Envelopes could not be exported and are not retriable. Error message:", restError.message);
2505
2637
  return { code: core.ExportResultCode.FAILED, error: restError };
2506
2638
  }
2507
2639
  }
2508
2640
  // Disable collection of statsbeat metrics after max failures
2509
2641
  _incrementStatsbeatFailure() {
2510
- var _a;
2642
+ var _a, _b;
2511
2643
  this._statsbeatFailureCount++;
2512
2644
  if (this._statsbeatFailureCount > MAX_STATSBEAT_FAILURES) {
2513
2645
  this._isStatsbeatExporter = false;
2514
- (_a = this._statsbeatMetrics) === null || _a === void 0 ? void 0 : _a.shutdown();
2515
- this._statsbeatMetrics = undefined;
2646
+ (_a = this._networkStatsbeatMetrics) === null || _a === void 0 ? void 0 : _a.shutdown();
2647
+ (_b = this._longIntervalStatsbeatMetrics) === null || _b === void 0 ? void 0 : _b.shutdown();
2648
+ this._networkStatsbeatMetrics = undefined;
2516
2649
  this._statsbeatFailureCount = 0;
2517
2650
  }
2518
2651
  }
@@ -2537,7 +2670,7 @@ class AzureMonitorBaseExporter {
2537
2670
 
2538
2671
  // Copyright (c) Microsoft Corporation.
2539
2672
  function createTagsFromResource(resource) {
2540
- const context = getInstance();
2673
+ const context = getInstance$1();
2541
2674
  const tags = Object.assign({}, context.tags);
2542
2675
  if (resource && resource.attributes) {
2543
2676
  const serviceName = resource.attributes[semanticConventions.SemanticResourceAttributes.SERVICE_NAME];
@@ -2729,7 +2862,7 @@ function createTagsFromSpan(span) {
2729
2862
  }
2730
2863
  else if (httpUrl) {
2731
2864
  try {
2732
- let url$1 = new url.URL(String(httpUrl));
2865
+ const url$1 = new url.URL(String(httpUrl));
2733
2866
  tags[KnownContextTagKeys.AiOperationName] = `${httpMethod} ${url$1.pathname}`;
2734
2867
  }
2735
2868
  catch (ex) { }
@@ -2755,19 +2888,23 @@ function createPropertiesFromSpanAttributes(attributes) {
2755
2888
  const properties = {};
2756
2889
  if (attributes) {
2757
2890
  for (const key of Object.keys(attributes)) {
2758
- if (!(key.startsWith("http.") ||
2759
- key.startsWith("rpc.") ||
2760
- key.startsWith("db.") ||
2761
- key.startsWith("peer.") ||
2762
- key.startsWith("message.") ||
2763
- key.startsWith("messaging.") ||
2764
- key.startsWith("enduser.") ||
2765
- key.startsWith("net.") ||
2766
- key.startsWith("exception.") ||
2767
- key.startsWith("thread.") ||
2768
- key.startsWith("faas.") ||
2769
- key.startsWith("code.") ||
2770
- key.startsWith("_MS."))) {
2891
+ // Avoid duplication ignoring fields already mapped.
2892
+ if (!(key.startsWith("_MS.") ||
2893
+ key == semanticConventions.SemanticAttributes.NET_PEER_IP ||
2894
+ key == semanticConventions.SemanticAttributes.NET_PEER_NAME ||
2895
+ key == semanticConventions.SemanticAttributes.PEER_SERVICE ||
2896
+ key == semanticConventions.SemanticAttributes.HTTP_METHOD ||
2897
+ key == semanticConventions.SemanticAttributes.HTTP_URL ||
2898
+ key == semanticConventions.SemanticAttributes.HTTP_STATUS_CODE ||
2899
+ key == semanticConventions.SemanticAttributes.HTTP_ROUTE ||
2900
+ key == semanticConventions.SemanticAttributes.HTTP_HOST ||
2901
+ key == semanticConventions.SemanticAttributes.HTTP_URL ||
2902
+ key == semanticConventions.SemanticAttributes.DB_SYSTEM ||
2903
+ key == semanticConventions.SemanticAttributes.DB_STATEMENT ||
2904
+ key == semanticConventions.SemanticAttributes.DB_OPERATION ||
2905
+ key == semanticConventions.SemanticAttributes.DB_NAME ||
2906
+ key == semanticConventions.SemanticAttributes.RPC_SYSTEM ||
2907
+ key == semanticConventions.SemanticAttributes.RPC_GRPC_STATUS_CODE)) {
2771
2908
  properties[key] = attributes[key];
2772
2909
  }
2773
2910
  }
@@ -2810,7 +2947,7 @@ function createDependencyData(span) {
2810
2947
  const httpUrl = span.attributes[semanticConventions.SemanticAttributes.HTTP_URL];
2811
2948
  if (httpUrl) {
2812
2949
  try {
2813
- let dependencyUrl = new url.URL(String(httpUrl));
2950
+ const dependencyUrl = new url.URL(String(httpUrl));
2814
2951
  remoteDependencyData.name = `${httpMethod} ${dependencyUrl.pathname}`;
2815
2952
  }
2816
2953
  catch (ex) { }
@@ -2825,11 +2962,11 @@ function createDependencyData(span) {
2825
2962
  if (target) {
2826
2963
  try {
2827
2964
  // Remove default port
2828
- let portRegex = new RegExp(/(https?)(:\/\/.*)(:\d+)(\S*)/);
2829
- let res = portRegex.exec(target);
2965
+ const portRegex = new RegExp(/(https?)(:\/\/.*)(:\d+)(\S*)/);
2966
+ const res = portRegex.exec(target);
2830
2967
  if (res != null) {
2831
- let protocol = res[1];
2832
- let port = res[3];
2968
+ const protocol = res[1];
2969
+ const port = res[3];
2833
2970
  if ((protocol == "https" && port == ":443") || (protocol == "http" && port == ":80")) {
2834
2971
  // Drop port
2835
2972
  target = res[1] + res[2] + res[4];
@@ -2869,7 +3006,7 @@ function createDependencyData(span) {
2869
3006
  else if (dbOperation) {
2870
3007
  remoteDependencyData.data = String(dbOperation);
2871
3008
  }
2872
- let target = getDependencyTarget(span.attributes);
3009
+ const target = getDependencyTarget(span.attributes);
2873
3010
  const dbName = span.attributes[semanticConventions.SemanticAttributes.DB_NAME];
2874
3011
  if (target) {
2875
3012
  remoteDependencyData.target = dbName ? `${target}|${dbName}` : `${target}`;
@@ -2885,7 +3022,7 @@ function createDependencyData(span) {
2885
3022
  if (grpcStatusCode) {
2886
3023
  remoteDependencyData.resultCode = String(grpcStatusCode);
2887
3024
  }
2888
- let target = getDependencyTarget(span.attributes);
3025
+ const target = getDependencyTarget(span.attributes);
2889
3026
  if (target) {
2890
3027
  remoteDependencyData.target = `${target}`;
2891
3028
  }
@@ -2982,18 +3119,18 @@ function readableSpanToEnvelope(span, ikey) {
2982
3119
  * @internal
2983
3120
  */
2984
3121
  function spanEventsToEnvelopes(span, ikey) {
2985
- let envelopes = [];
3122
+ const envelopes = [];
2986
3123
  if (span.events) {
2987
3124
  span.events.forEach((event) => {
2988
3125
  var _a;
2989
3126
  let baseType;
2990
- let time = new Date(core.hrTimeToMilliseconds(event.time));
3127
+ const time = new Date(core.hrTimeToMilliseconds(event.time));
2991
3128
  let name = "";
2992
3129
  let baseData;
2993
3130
  const properties = createPropertiesFromSpanAttributes(event.attributes);
2994
- let tags = createTagsFromResource(span.resource);
3131
+ const tags = createTagsFromResource(span.resource);
2995
3132
  tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;
2996
- let spanId = (_a = span.spanContext()) === null || _a === void 0 ? void 0 : _a.spanId;
3133
+ const spanId = (_a = span.spanContext()) === null || _a === void 0 ? void 0 : _a.spanId;
2997
3134
  if (spanId) {
2998
3135
  tags[KnownContextTagKeys.AiOperationParentId] = spanId;
2999
3136
  }
@@ -3011,22 +3148,22 @@ function spanEventsToEnvelopes(span, ikey) {
3011
3148
  if (stack) {
3012
3149
  hasFullStack = true;
3013
3150
  }
3014
- let exceptionMsg = event.attributes[semanticConventions.SemanticAttributes.EXCEPTION_MESSAGE];
3151
+ const exceptionMsg = event.attributes[semanticConventions.SemanticAttributes.EXCEPTION_MESSAGE];
3015
3152
  if (exceptionMsg) {
3016
3153
  message = String(exceptionMsg);
3017
3154
  }
3018
- let escaped = event.attributes[semanticConventions.SemanticAttributes.EXCEPTION_ESCAPED];
3155
+ const escaped = event.attributes[semanticConventions.SemanticAttributes.EXCEPTION_ESCAPED];
3019
3156
  if (escaped != undefined) {
3020
3157
  properties[semanticConventions.SemanticAttributes.EXCEPTION_ESCAPED] = String(escaped);
3021
3158
  }
3022
3159
  }
3023
- let exceptionDetails = {
3160
+ const exceptionDetails = {
3024
3161
  typeName: typeName,
3025
3162
  message: message,
3026
3163
  stack: stack,
3027
3164
  hasFullStack: hasFullStack,
3028
3165
  };
3029
- let exceptionData = {
3166
+ const exceptionData = {
3030
3167
  exceptions: [exceptionDetails],
3031
3168
  version: 2,
3032
3169
  properties: properties,
@@ -3036,7 +3173,7 @@ function spanEventsToEnvelopes(span, ikey) {
3036
3173
  else {
3037
3174
  name = "Microsoft.ApplicationInsights.Message";
3038
3175
  baseType = "MessageData";
3039
- let messageData = {
3176
+ const messageData = {
3040
3177
  message: event.name,
3041
3178
  version: 2,
3042
3179
  properties: properties,
@@ -3047,7 +3184,7 @@ function spanEventsToEnvelopes(span, ikey) {
3047
3184
  if (span.attributes[AzureMonitorSampleRate]) {
3048
3185
  sampleRate = Number(span.attributes[AzureMonitorSampleRate]);
3049
3186
  }
3050
- let env = {
3187
+ const env = {
3051
3188
  name: name,
3052
3189
  time: time,
3053
3190
  instrumentationKey: ikey,
@@ -3142,20 +3279,13 @@ function resourceMetricsToEnvelope(metrics, ikey, isStatsbeat) {
3142
3279
  }
3143
3280
  metrics.scopeMetrics.forEach((scopeMetric) => {
3144
3281
  scopeMetric.metrics.forEach((metric) => {
3145
- var _a, _b;
3146
- const isStandardMetric = (_b = (_a = metric.descriptor) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.startsWith("azureMonitor.");
3147
3282
  metric.dataPoints.forEach((dataPoint) => {
3148
3283
  let baseData = {
3149
3284
  metrics: [],
3150
3285
  version: 2,
3151
3286
  properties: {},
3152
3287
  };
3153
- if (isStandardMetric) {
3154
- baseData.properties = createStandardMetricsProperties(metric.descriptor.name, dataPoint.attributes, tags);
3155
- }
3156
- else {
3157
- baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);
3158
- }
3288
+ baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);
3159
3289
  var metricDataPoint = {
3160
3290
  name: metric.descriptor.name,
3161
3291
  value: 0,
@@ -3191,37 +3321,6 @@ function resourceMetricsToEnvelope(metrics, ikey, isStatsbeat) {
3191
3321
  });
3192
3322
  return envelopes;
3193
3323
  }
3194
- function createStandardMetricsProperties(name, attributes, tags) {
3195
- const properties = {};
3196
- properties[PreAggregatedMetricPropertyNames.IsAutocollected] = "True";
3197
- properties[PreAggregatedMetricPropertyNames.cloudRoleInstance] =
3198
- tags[KnownContextTagKeys.AiCloudRoleInstance];
3199
- properties[PreAggregatedMetricPropertyNames.cloudRoleName] =
3200
- tags[KnownContextTagKeys.AiCloudRole];
3201
- if (name == StandardMetrics.HTTP_REQUEST_DURATION) {
3202
- properties[PreAggregatedMetricPropertyNames.metricId] = StandardMetricIds.REQUEST_DURATION;
3203
- let statusCode = String(attributes["http.status_code"]);
3204
- properties[PreAggregatedMetricPropertyNames.requestResultCode] = statusCode;
3205
- properties[PreAggregatedMetricPropertyNames.requestSuccess] =
3206
- statusCode == "200" ? "True" : "False";
3207
- }
3208
- else if (name == StandardMetrics.HTTP_DEPENDENCY_DURATION) {
3209
- properties[PreAggregatedMetricPropertyNames.metricId] = StandardMetricIds.DEPENDENCY_DURATION;
3210
- let statusCode = String(attributes["http.status_code"]);
3211
- properties[PreAggregatedMetricPropertyNames.dependencyTarget] = getDependencyTarget(attributes);
3212
- properties[PreAggregatedMetricPropertyNames.dependencyResultCode] = statusCode;
3213
- properties[PreAggregatedMetricPropertyNames.dependencyType] = "http";
3214
- properties[PreAggregatedMetricPropertyNames.dependencySuccess] =
3215
- statusCode == "200" ? "True" : "False";
3216
- }
3217
- else if (name == StandardMetrics.TRACE_COUNT) {
3218
- properties[PreAggregatedMetricPropertyNames.metricId] = StandardMetricIds.TRACE_COUNT;
3219
- }
3220
- else if (name == StandardMetrics.EXCEPTION_COUNT) {
3221
- properties[PreAggregatedMetricPropertyNames.metricId] = StandardMetricIds.EXCEPTION_COUNT;
3222
- }
3223
- return properties;
3224
- }
3225
3324
 
3226
3325
  // Copyright (c) Microsoft Corporation.
3227
3326
  /**
@@ -3283,10 +3382,9 @@ class AzureMonitorMetricExporter extends AzureMonitorBaseExporter {
3283
3382
 
3284
3383
  // Copyright (c) Microsoft Corporation.
3285
3384
  /**
3286
- * @internal
3287
3385
  * Azure Monitor Statsbeat Exporter
3288
3386
  */
3289
- class _AzureMonitorStatsbeatExporter extends AzureMonitorBaseExporter {
3387
+ class AzureMonitorStatsbeatExporter extends AzureMonitorBaseExporter {
3290
3388
  /**
3291
3389
  * Initializes a new instance of the AzureMonitorStatsbeatExporter class.
3292
3390
  * @param options - Exporter configuration
@@ -3331,6 +3429,6 @@ class _AzureMonitorStatsbeatExporter extends AzureMonitorBaseExporter {
3331
3429
  exports.ApplicationInsightsSampler = ApplicationInsightsSampler;
3332
3430
  exports.AzureMonitorBaseExporter = AzureMonitorBaseExporter;
3333
3431
  exports.AzureMonitorMetricExporter = AzureMonitorMetricExporter;
3432
+ exports.AzureMonitorStatsbeatExporter = AzureMonitorStatsbeatExporter;
3334
3433
  exports.AzureMonitorTraceExporter = AzureMonitorTraceExporter;
3335
- exports._AzureMonitorStatsbeatExporter = _AzureMonitorStatsbeatExporter;
3336
3434
  //# sourceMappingURL=index.js.map