@azure/monitor-opentelemetry-exporter 1.0.0-beta.8 → 1.0.0-beta.9
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 +47 -9
- package/dist/index.js +294 -134
- package/dist-esm/src/config.js +1 -14
- package/dist-esm/src/config.js.map +1 -1
- package/dist-esm/src/export/base.js +20 -18
- package/dist-esm/src/export/base.js.map +1 -1
- package/dist-esm/src/export/metric.js +22 -8
- package/dist-esm/src/export/metric.js.map +1 -1
- package/dist-esm/src/export/trace.js +12 -1
- package/dist-esm/src/export/trace.js.map +1 -1
- package/dist-esm/src/generated/applicationInsightsClient.js +36 -3
- package/dist-esm/src/generated/applicationInsightsClient.js.map +1 -1
- package/dist-esm/src/generated/index.js +0 -1
- package/dist-esm/src/generated/index.js.map +1 -1
- package/dist-esm/src/generated/models/index.js +35 -0
- package/dist-esm/src/generated/models/index.js.map +1 -1
- package/dist-esm/src/index.js +1 -0
- package/dist-esm/src/index.js.map +1 -1
- package/dist-esm/src/platform/nodejs/httpSender.js +5 -8
- package/dist-esm/src/platform/nodejs/httpSender.js.map +1 -1
- package/dist-esm/src/platform/nodejs/persist/fileSystemHelpers.js +2 -1
- package/dist-esm/src/platform/nodejs/persist/fileSystemHelpers.js.map +1 -1
- package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js +10 -5
- package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js.map +1 -1
- package/dist-esm/src/sampling.js +81 -0
- package/dist-esm/src/sampling.js.map +1 -0
- package/dist-esm/src/utils/breezeUtils.js +3 -1
- package/dist-esm/src/utils/breezeUtils.js.map +1 -1
- package/dist-esm/src/utils/constants/applicationinsights.js +2 -1
- package/dist-esm/src/utils/constants/applicationinsights.js.map +1 -1
- package/dist-esm/src/utils/metricUtils.js +34 -20
- package/dist-esm/src/utils/metricUtils.js.map +1 -1
- package/dist-esm/src/utils/spanUtils.js +21 -11
- package/dist-esm/src/utils/spanUtils.js.map +1 -1
- package/package.json +14 -14
- package/types/monitor-opentelemetry-exporter.d.ts +94 -24
- package/dist-esm/src/generated/applicationInsightsClientContext.js +0 -34
- package/dist-esm/src/generated/applicationInsightsClientContext.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { AzureMonitorBaseExporter } from \"./export/base\";\nexport { AzureMonitorTraceExporter } from \"./export/trace\";\nexport { AzureMonitorMetricExporter } from \"./export/metric\";\nexport {
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { ApplicationInsightsSampler } from \"./sampling\";\nexport { AzureMonitorBaseExporter } from \"./export/base\";\nexport { AzureMonitorTraceExporter } from \"./export/trace\";\nexport { AzureMonitorMetricExporter } from \"./export/metric\";\nexport { AzureMonitorExporterOptions } from \"./config\";\nexport { ServiceApiVersion } from \"./Declarations/Constants\";\nexport {\n ApplicationInsightsClientOptionalParams,\n MonitorBase,\n MonitorDomain,\n TelemetryItem,\n} from \"./generated/models\";\n"]}
|
|
@@ -10,19 +10,16 @@ const applicationInsightsResource = "https://monitor.azure.com//.default";
|
|
|
10
10
|
* @internal
|
|
11
11
|
*/
|
|
12
12
|
export class HttpSender {
|
|
13
|
-
constructor(
|
|
14
|
-
this._exporterOptions = _exporterOptions;
|
|
13
|
+
constructor(endpointUrl, options) {
|
|
15
14
|
// Build endpoint using provided configuration or default values
|
|
16
|
-
this._appInsightsClientOptions = {
|
|
17
|
-
|
|
18
|
-
};
|
|
19
|
-
this._appInsightsClient = new ApplicationInsightsClient(Object.assign({}, this._appInsightsClientOptions));
|
|
15
|
+
this._appInsightsClientOptions = Object.assign({ host: endpointUrl }, options);
|
|
16
|
+
this._appInsightsClient = new ApplicationInsightsClient(this._appInsightsClientOptions);
|
|
20
17
|
// Handle redirects in HTTP Sender
|
|
21
18
|
this._appInsightsClient.pipeline.removePolicy({ name: redirectPolicyName });
|
|
22
|
-
if (
|
|
19
|
+
if (options === null || options === void 0 ? void 0 : options.aadTokenCredential) {
|
|
23
20
|
let scopes = [applicationInsightsResource];
|
|
24
21
|
this._appInsightsClient.pipeline.addPolicy(bearerTokenAuthenticationPolicy({
|
|
25
|
-
credential:
|
|
22
|
+
credential: options === null || options === void 0 ? void 0 : options.aadTokenCredential,
|
|
26
23
|
scopes: scopes,
|
|
27
24
|
}));
|
|
28
25
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpSender.js","sourceRoot":"","sources":["../../../../src/platform/nodejs/httpSender.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,+BAA+B,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAEhG,OAAO,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QAC9B,IAAI,OAAO,GAAwB,EAAE,CAAC;QACtC,IAAI;YACF,IAAI,QAA2C,CAAC;YAChD,SAAS,UAAU,CAAC,WAAkC,EAAE,YAAqB;gBAC3E,QAAQ,GAAG,WAAW,CAAC;gBACvB,IAAI,OAAO,CAAC,UAAU,EAAE;oBACtB,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;iBAC/C;YACH,CAAC;YACD,MAAM,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,SAAS,kCACxC,OAAO,KACV,UAAU,IACV,CAAC;YAEH,OAAO,EAAE,UAAU,EAAE,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,MAAM,EAAE,MAAM,EAAE,MAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,UAAU,mCAAI,EAAE,EAAE,CAAC;SAC7E;QAAC,OAAO,CAAM,EAAE;YACf,MAAM,CAAC,CAAC;SACT;IACH,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,QAAQ;QACZ,IAAI,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC;IACxC,CAAC;IAED,uBAAuB,CAAC,QAA4B;QAClD,IAAI,QAAQ,EAAE;YACZ,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACrC,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE;gBACzB,IAAI,CAAC,kBAAkB,CAAC,IAAI,GAAG,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC;aACzD;SACF;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport url from \"url\";\nimport { diag } from \"@opentelemetry/api\";\nimport { FullOperationResponse } from \"@azure/core-client\";\nimport { bearerTokenAuthenticationPolicy, redirectPolicyName } from \"@azure/core-rest-pipeline\";\nimport { Sender, SenderResult } from \"../../types\";\nimport {\n TelemetryItem as Envelope,\n ApplicationInsightsClient,\n ApplicationInsightsClientOptionalParams,\n TrackOptionalParams,\n} from \"../../generated\";\nimport { AzureMonitorExporterOptions } from \"../../config\";\n\nconst applicationInsightsResource = \"https://monitor.azure.com//.default\";\n\n/**\n * Exporter HTTP sender class\n * @internal\n */\nexport class HttpSender implements Sender {\n private readonly _appInsightsClient: ApplicationInsightsClient;\n private _appInsightsClientOptions: ApplicationInsightsClientOptionalParams;\n\n constructor(endpointUrl: string, options?: AzureMonitorExporterOptions) {\n // Build endpoint using provided configuration or default values\n this._appInsightsClientOptions = {\n host: endpointUrl,\n ...options,\n };\n this._appInsightsClient = new ApplicationInsightsClient(this._appInsightsClientOptions);\n\n // Handle redirects in HTTP Sender\n this._appInsightsClient.pipeline.removePolicy({ name: redirectPolicyName });\n\n if (options?.aadTokenCredential) {\n let scopes: string[] = [applicationInsightsResource];\n this._appInsightsClient.pipeline.addPolicy(\n bearerTokenAuthenticationPolicy({\n credential: options?.aadTokenCredential,\n scopes: scopes,\n })\n );\n }\n }\n\n /**\n * Send Azure envelopes\n * @internal\n */\n async send(envelopes: Envelope[]): Promise<SenderResult> {\n let options: TrackOptionalParams = {};\n try {\n let response: FullOperationResponse | undefined;\n function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {\n response = rawResponse;\n if (options.onResponse) {\n options.onResponse(rawResponse, flatResponse);\n }\n }\n await this._appInsightsClient.track(envelopes, {\n ...options,\n onResponse,\n });\n\n return { statusCode: response?.status, result: response?.bodyAsText ?? \"\" };\n } catch (e: any) {\n throw e;\n }\n }\n\n /**\n * Shutdown sender\n * @internal\n */\n async shutdown(): Promise<void> {\n diag.info(\"HttpSender shutting down\");\n }\n\n handlePermanentRedirect(location: string | undefined) {\n if (location) {\n const locUrl = new url.URL(location);\n if (locUrl && locUrl.host) {\n this._appInsightsClient.host = \"https://\" + locUrl.host;\n }\n }\n }\n}\n"]}
|
|
@@ -38,7 +38,8 @@ export const confirmDirExists = async (directory) => {
|
|
|
38
38
|
catch (err) {
|
|
39
39
|
if (err && err.code === "ENOENT") {
|
|
40
40
|
try {
|
|
41
|
-
|
|
41
|
+
const options = { recursive: true };
|
|
42
|
+
await mkdirAsync(directory, options);
|
|
42
43
|
}
|
|
43
44
|
catch (mkdirErr) {
|
|
44
45
|
if (mkdirErr && mkdirErr.code !== "EEXIST") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileSystemHelpers.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemHelpers.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,UAAU,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AACvC,MAAM,UAAU,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AAEvC;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,EAAE,SAAiB,EAAmB,EAAE;IAClF,4BAA4B;IAC5B,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,SAAS,CAAC,CAAC;IAE5C,IAAI,SAAS,GAAG,CAAC,CAAC;IAElB,uBAAuB;IACvB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACxB,MAAM,SAAS,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9D,IAAI,SAAS,CAAC,MAAM,EAAE,EAAE;YACtB,SAAS,IAAI,SAAS,CAAC,IAAI,CAAC;SAC7B;KACF;IAED,OAAO,SAAS,CAAC;AACnB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AG,MAAM,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9D,IAAI,SAAS,CAAC,MAAM,EAAE,EAAE;YACtB,SAAS,IAAI,SAAS,CAAC,IAAI,CAAC;SAC7B;KACF;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,EAAE,SAAiB,EAAiB,EAAE;IACzE,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;SACzD;KACF;IAAC,OAAO,GAAQ,EAAE;QACjB,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,IAAI;gBACF,MAAM,OAAO,GAA4B,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;gBAC7D,MAAM,UAAU,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;aACtC;YAAC,OAAO,QAAa,EAAE;gBACtB,IAAI,QAAQ,IAAI,QAAQ,CAAC,IAAI,KAAK,QAAQ,EAAE;oBAC1C,2CAA2C;oBAC3C,MAAM,QAAQ,CAAC;iBAChB;aACF;SACF;KACF;AACH,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { promisify } from \"util\";\n\nconst readdirAsync = promisify(fs.readdir);\nconst statAsync = promisify(fs.stat);\nconst lstatAsync = promisify(fs.lstat);\nconst mkdirAsync = promisify(fs.mkdir);\n\n/**\n * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously.\n * @internal\n */\nexport const getShallowDirectorySize = async (directory: string): Promise<number> => {\n // Get the directory listing\n const files = await readdirAsync(directory);\n\n let totalSize = 0;\n\n // Query all file sizes\n for (const file of files) {\n const fileStats = await statAsync(path.join(directory, file));\n if (fileStats.isFile()) {\n totalSize += fileStats.size;\n }\n }\n\n return totalSize;\n};\n\n/**\n * Validate directory exists.\n * @internal\n */\nexport const confirmDirExists = async (directory: string): Promise<void> => {\n try {\n const stats = await lstatAsync(directory);\n if (!stats.isDirectory()) {\n throw new Error(\"Path existed but was not a directory\");\n }\n } catch (err: any) {\n if (err && err.code === \"ENOENT\") {\n try {\n const options: fs.MakeDirectoryOptions = { recursive: true };\n await mkdirAsync(directory, options);\n } catch (mkdirErr: any) {\n if (mkdirErr && mkdirErr.code !== \"EEXIST\") {\n // Handle race condition by ignoring EEXIST\n throw mkdirErr;\n }\n }\n }\n }\n};\n"]}
|
|
@@ -4,7 +4,6 @@ import * as fs from "fs";
|
|
|
4
4
|
import * as os from "os";
|
|
5
5
|
import * as path from "path";
|
|
6
6
|
import { diag } from "@opentelemetry/api";
|
|
7
|
-
import { DEFAULT_EXPORTER_CONFIG } from "../../../config";
|
|
8
7
|
import { FileAccessControl } from "./fileAccessControl";
|
|
9
8
|
import { confirmDirExists, getShallowDirectorySize } from "./fileSystemHelpers";
|
|
10
9
|
import { promisify } from "util";
|
|
@@ -18,25 +17,31 @@ const writeFileAsync = promisify(fs.writeFile);
|
|
|
18
17
|
* @internal
|
|
19
18
|
*/
|
|
20
19
|
export class FileSystemPersist {
|
|
21
|
-
constructor(
|
|
20
|
+
constructor(instrumentationKey, _options) {
|
|
21
|
+
var _a, _b;
|
|
22
|
+
this._options = _options;
|
|
22
23
|
this.fileRetemptionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
23
24
|
this.cleanupTimeOut = 60 * 60 * 1000; // 1 hour
|
|
24
25
|
this.maxBytesOnDisk = 50000000; // ~50MB
|
|
25
26
|
this._tempDirectory = "";
|
|
26
27
|
this._fileCleanupTimer = null;
|
|
27
|
-
this.
|
|
28
|
+
this._instrumentationKey = instrumentationKey;
|
|
29
|
+
if ((_a = this._options) === null || _a === void 0 ? void 0 : _a.disableOfflineStorage) {
|
|
30
|
+
this._enabled = false;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
28
33
|
this._enabled = true;
|
|
29
34
|
FileAccessControl.checkFileProtection();
|
|
30
35
|
if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {
|
|
31
36
|
this._enabled = false;
|
|
32
37
|
diag.error("Sufficient file protection capabilities were not detected. Files will not be persisted");
|
|
33
38
|
}
|
|
34
|
-
if (!this.
|
|
39
|
+
if (!this._instrumentationKey) {
|
|
35
40
|
this._enabled = false;
|
|
36
41
|
diag.error(`No instrumentation key was provided to FileSystemPersister. Files will not be persisted`);
|
|
37
42
|
}
|
|
38
43
|
if (this._enabled) {
|
|
39
|
-
this._tempDirectory = path.join(os.tmpdir(), FileSystemPersist.TEMPDIR_PREFIX + this.
|
|
44
|
+
this._tempDirectory = path.join(((_b = this._options) === null || _b === void 0 ? void 0 : _b.storageDirectory) || os.tmpdir(), "Microsoft", "AzureMonitor", FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey);
|
|
40
45
|
// Starts file cleanup task
|
|
41
46
|
if (!this._fileCleanupTimer) {
|
|
42
47
|
this._fileCleanupTimer = setTimeout(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileSystemPersist.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,uBAAuB,EAA+B,MAAM,iBAAiB,CAAC;AACvF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,gBAA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gBACvB,MAAM,SAAS,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;gBAC1D,MAAM,KAAK,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CACnC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAC7D,CAAC;gBACF,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;oBACtB,OAAO,KAAK,CAAC;iBACd;qBAAM;oBACL,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;wBAC3B,mBAAmB;wBACnB,MAAM,gBAAgB,GAAS,IAAI,IAAI,CACrC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAC3D,CAAC;wBACF,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,EAAE,GAAG,IAAI,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC;wBACrF,IAAI,OAAO,EAAE;4BACX,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;4BACtD,MAAM,WAAW,CAAC,QAAQ,CAAC,CAAC;yBAC7B;oBACH,CAAC,CAAC,CAAC;oBACH,OAAO,IAAI,CAAC;iBACb;aACF;YACD,OAAO,KAAK,CAAC;SACd;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;SACd;IACH,CAAC;;AA9KM,gCAAc,GAAG,oBAAoB,CAAC;AAEtC,iCAAe,GAAG,UAAU,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { diag } from \"@opentelemetry/api\";\nimport { PersistentStorage } from \"../../../types\";\nimport { DEFAULT_EXPORTER_CONFIG, AzureExporterInternalConfig } from \"../../../config\";\nimport { FileAccessControl } from \"./fileAccessControl\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\n\nconst statAsync = promisify(fs.stat);\nconst readdirAsync = promisify(fs.readdir);\nconst readFileAsync = promisify(fs.readFile);\nconst unlinkAsync = promisify(fs.unlink);\nconst writeFileAsync = promisify(fs.writeFile);\n\n/**\n * File system persist class.\n * @internal\n */\nexport class FileSystemPersist implements PersistentStorage {\n static TEMPDIR_PREFIX = \"ot-azure-exporter-\";\n\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 days\n cleanupTimeOut = 60 * 60 * 1000; // 1 hour\n maxBytesOnDisk: number = 50_000_000; // ~50MB\n\n private _enabled: boolean;\n private _tempDirectory: string = \"\";\n private _fileCleanupTimer: NodeJS.Timer | null = null;\n\n private readonly _options: AzureExporterInternalConfig;\n\n constructor(options: Partial<AzureExporterInternalConfig> = {}) {\n this._options = { ...DEFAULT_EXPORTER_CONFIG, ...options };\n this._enabled = true;\n FileAccessControl.checkFileProtection();\n\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n this._enabled = false;\n diag.error(\n \"Sufficient file protection capabilities were not detected. Files will not be persisted\"\n );\n }\n\n if (!this._options.instrumentationKey) {\n this._enabled = false;\n diag.error(\n `No instrumentation key was provided to FileSystemPersister. Files will not be persisted`\n );\n }\n if (this._enabled) {\n this._tempDirectory = path.join(\n os.tmpdir(),\n FileSystemPersist.TEMPDIR_PREFIX + this._options.instrumentationKey\n );\n // Starts file cleanup task\n if (!this._fileCleanupTimer) {\n this._fileCleanupTimer = setTimeout(() => {\n this._fileCleanupTask();\n }, this.cleanupTimeOut);\n this._fileCleanupTimer.unref();\n }\n }\n }\n\n push(value: unknown[]): Promise<boolean> {\n if (this._enabled) {\n diag.debug(\"Pushing value to persistent storage\", value.toString());\n return this._storeToDisk(JSON.stringify(value));\n }\n return new Promise((resolve) => {\n resolve(false);\n });\n }\n\n async shift(): Promise<unknown> {\n if (this._enabled) {\n diag.debug(\"Searching for filesystem persisted files\");\n try {\n const buffer = await this._getFirstFileOnDisk();\n if (buffer) {\n return JSON.parse(buffer.toString(\"utf8\"));\n }\n } catch (e: any) {\n diag.debug(\"Failed to read persisted file\", e);\n }\n return null;\n }\n return new Promise((resolve) => {\n resolve(null);\n });\n }\n\n /**\n * Check for temp telemetry files\n * reads the first file if exist, deletes it and tries to send its load\n */\n private async _getFirstFileOnDisk(): Promise<Buffer | null> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX)\n );\n if (files.length === 0) {\n return null;\n } else {\n const firstFile = files[0];\n const filePath = path.join(this._tempDirectory, firstFile);\n const payload = await readFileAsync(filePath);\n // delete the file first to prevent double sending\n await unlinkAsync(filePath);\n return payload;\n }\n }\n return null;\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // File does not exist -- return null instead of throwing\n return null;\n } else {\n throw e;\n }\n }\n }\n\n private async _storeToDisk(payload: string): Promise<boolean> {\n try {\n await confirmDirExists(this._tempDirectory);\n } catch (error: any) {\n diag.warn(`Error while checking/creating directory: `, error && error.message);\n return false;\n }\n\n try {\n const size = await getShallowDirectorySize(this._tempDirectory);\n if (size > this.maxBytesOnDisk) {\n diag.warn(\n `Not saving data due to max size limit being met. Directory size in bytes is: ${size}`\n );\n return false;\n }\n } catch (error: any) {\n diag.warn(`Error while checking size of persistence directory: `, error && error.message);\n return false;\n }\n\n const fileName = `${new Date().getTime()}${FileSystemPersist.FILENAME_SUFFIX}`;\n const fileFullPath = path.join(this._tempDirectory, fileName);\n\n // Mode 600 is w/r for creator and no read access for others\n diag.info(`saving data to disk at: ${fileFullPath}`);\n try {\n await writeFileAsync(fileFullPath, payload, { mode: 0o600 });\n } catch (writeError: any) {\n diag.warn(`Error writing file to persistent file storage`, writeError);\n return false;\n }\n return true;\n }\n\n private async _fileCleanupTask(): Promise<boolean> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX)\n );\n if (files.length === 0) {\n return false;\n } else {\n files.forEach(async (file) => {\n // Check expiration\n const fileCreationDate: Date = new Date(\n parseInt(file.split(FileSystemPersist.FILENAME_SUFFIX)[0])\n );\n const expired = new Date(+new Date() - this.fileRetemptionPeriod) > fileCreationDate;\n if (expired) {\n const filePath = path.join(this._tempDirectory, file);\n await unlinkAsync(filePath);\n }\n });\n return true;\n }\n }\n return false;\n } catch (error: any) {\n diag.info(`Failed cleanup of persistent file storage expired files`, error);\n return false;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fileSystemPersist.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAGjC,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE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B,MAAM,SAAS,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;gBAC1D,MAAM,KAAK,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CACnC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAC7D,CAAC;gBACF,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;oBACtB,OAAO,KAAK,CAAC;iBACd;qBAAM;oBACL,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;wBAC3B,mBAAmB;wBACnB,MAAM,gBAAgB,GAAS,IAAI,IAAI,CACrC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAC3D,CAAC;wBACF,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,EAAE,GAAG,IAAI,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC;wBACrF,IAAI,OAAO,EAAE;4BACX,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;4BACtD,MAAM,WAAW,CAAC,QAAQ,CAAC,CAAC;yBAC7B;oBACH,CAAC,CAAC,CAAC;oBACH,OAAO,IAAI,CAAC;iBACb;aACF;YACD,OAAO,KAAK,CAAC;SACd;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;SACd;IACH,CAAC;;AAnLM,gCAAc,GAAG,oBAAoB,CAAC;AACtC,iCAAe,GAAG,UAAU,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { diag } from \"@opentelemetry/api\";\nimport { PersistentStorage } from \"../../../types\";\nimport { FileAccessControl } from \"./fileAccessControl\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\nimport { AzureMonitorExporterOptions } from \"../../../config\";\n\nconst statAsync = promisify(fs.stat);\nconst readdirAsync = promisify(fs.readdir);\nconst readFileAsync = promisify(fs.readFile);\nconst unlinkAsync = promisify(fs.unlink);\nconst writeFileAsync = promisify(fs.writeFile);\n\n/**\n * File system persist class.\n * @internal\n */\nexport class FileSystemPersist implements PersistentStorage {\n static TEMPDIR_PREFIX = \"ot-azure-exporter-\";\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 days\n cleanupTimeOut = 60 * 60 * 1000; // 1 hour\n maxBytesOnDisk: number = 50_000_000; // ~50MB\n\n private _enabled: boolean;\n private _tempDirectory: string = \"\";\n private _fileCleanupTimer: NodeJS.Timer | null = null;\n private _instrumentationKey: string;\n\n constructor(instrumentationKey: string, private _options?: AzureMonitorExporterOptions) {\n this._instrumentationKey = instrumentationKey;\n if (this._options?.disableOfflineStorage) {\n this._enabled = false;\n return;\n }\n this._enabled = true;\n FileAccessControl.checkFileProtection();\n\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n this._enabled = false;\n diag.error(\n \"Sufficient file protection capabilities were not detected. Files will not be persisted\"\n );\n }\n\n if (!this._instrumentationKey) {\n this._enabled = false;\n diag.error(\n `No instrumentation key was provided to FileSystemPersister. Files will not be persisted`\n );\n }\n if (this._enabled) {\n this._tempDirectory = path.join(\n this._options?.storageDirectory || os.tmpdir(),\n \"Microsoft\",\n \"AzureMonitor\",\n FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey\n );\n\n // Starts file cleanup task\n if (!this._fileCleanupTimer) {\n this._fileCleanupTimer = setTimeout(() => {\n this._fileCleanupTask();\n }, this.cleanupTimeOut);\n this._fileCleanupTimer.unref();\n }\n }\n }\n\n push(value: unknown[]): Promise<boolean> {\n if (this._enabled) {\n diag.debug(\"Pushing value to persistent storage\", value.toString());\n return this._storeToDisk(JSON.stringify(value));\n }\n return new Promise((resolve) => {\n resolve(false);\n });\n }\n\n async shift(): Promise<unknown> {\n if (this._enabled) {\n diag.debug(\"Searching for filesystem persisted files\");\n try {\n const buffer = await this._getFirstFileOnDisk();\n if (buffer) {\n return JSON.parse(buffer.toString(\"utf8\"));\n }\n } catch (e: any) {\n diag.debug(\"Failed to read persisted file\", e);\n }\n return null;\n }\n return new Promise((resolve) => {\n resolve(null);\n });\n }\n\n /**\n * Check for temp telemetry files\n * reads the first file if exist, deletes it and tries to send its load\n */\n private async _getFirstFileOnDisk(): Promise<Buffer | null> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX)\n );\n if (files.length === 0) {\n return null;\n } else {\n const firstFile = files[0];\n const filePath = path.join(this._tempDirectory, firstFile);\n const payload = await readFileAsync(filePath);\n // delete the file first to prevent double sending\n await unlinkAsync(filePath);\n return payload;\n }\n }\n return null;\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // File does not exist -- return null instead of throwing\n return null;\n } else {\n throw e;\n }\n }\n }\n\n private async _storeToDisk(payload: string): Promise<boolean> {\n try {\n await confirmDirExists(this._tempDirectory);\n } catch (error: any) {\n diag.warn(`Error while checking/creating directory: `, error && error.message);\n return false;\n }\n\n try {\n const size = await getShallowDirectorySize(this._tempDirectory);\n if (size > this.maxBytesOnDisk) {\n diag.warn(\n `Not saving data due to max size limit being met. Directory size in bytes is: ${size}`\n );\n return false;\n }\n } catch (error: any) {\n diag.warn(`Error while checking size of persistence directory: `, error && error.message);\n return false;\n }\n\n const fileName = `${new Date().getTime()}${FileSystemPersist.FILENAME_SUFFIX}`;\n const fileFullPath = path.join(this._tempDirectory, fileName);\n\n // Mode 600 is w/r for creator and no read access for others\n diag.info(`saving data to disk at: ${fileFullPath}`);\n try {\n await writeFileAsync(fileFullPath, payload, { mode: 0o600 });\n } catch (writeError: any) {\n diag.warn(`Error writing file to persistent file storage`, writeError);\n return false;\n }\n return true;\n }\n\n private async _fileCleanupTask(): Promise<boolean> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX)\n );\n if (files.length === 0) {\n return false;\n } else {\n files.forEach(async (file) => {\n // Check expiration\n const fileCreationDate: Date = new Date(\n parseInt(file.split(FileSystemPersist.FILENAME_SUFFIX)[0])\n );\n const expired = new Date(+new Date() - this.fileRetemptionPeriod) > fileCreationDate;\n if (expired) {\n const filePath = path.join(this._tempDirectory, file);\n await unlinkAsync(filePath);\n }\n });\n return true;\n }\n }\n return false;\n } catch (error: any) {\n diag.info(`Failed cleanup of persistent file storage expired files`, error);\n return false;\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { SamplingDecision } from "@opentelemetry/sdk-trace-base";
|
|
2
|
+
import { AzureMonitorSampleRate } from "./utils/constants/applicationinsights";
|
|
3
|
+
/**
|
|
4
|
+
* ApplicationInsightsSampler is responsible for the following:
|
|
5
|
+
* Implements same trace id hashing algorithm so that traces are sampled the same across multiple nodes
|
|
6
|
+
* Adds item count to span attribute if span is sampled (needed for ingestion service)
|
|
7
|
+
* @param samplingRatio - 0 to 1 value.
|
|
8
|
+
*/
|
|
9
|
+
export class ApplicationInsightsSampler {
|
|
10
|
+
constructor(samplingRatio = 1) {
|
|
11
|
+
this._samplingRatio = samplingRatio;
|
|
12
|
+
if (this._samplingRatio > 1) {
|
|
13
|
+
throw new Error("Wrong sampling rate, data will not be sampled out");
|
|
14
|
+
}
|
|
15
|
+
this._sampleRate = Math.round(this._samplingRatio * 100);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Checks whether span needs to be created and tracked.
|
|
19
|
+
*
|
|
20
|
+
* @param context Parent Context which may contain a span.
|
|
21
|
+
* @param traceId of the span to be created. It can be different from the
|
|
22
|
+
* traceId in the {@link SpanContext}. Typically in situations when the
|
|
23
|
+
* span to be created starts a new trace.
|
|
24
|
+
* @param spanName of the span to be created.
|
|
25
|
+
* @param spanKind of the span to be created.
|
|
26
|
+
* @param attributes Initial set of SpanAttributes for the Span being constructed.
|
|
27
|
+
* @param links Collection of links that will be associated with the Span to
|
|
28
|
+
* be created. Typically useful for batch operations.
|
|
29
|
+
* @returns a {@link SamplingResult}.
|
|
30
|
+
*/
|
|
31
|
+
shouldSample(
|
|
32
|
+
// @ts-ignore
|
|
33
|
+
context, traceId,
|
|
34
|
+
// @ts-ignore
|
|
35
|
+
spanName,
|
|
36
|
+
// @ts-ignore
|
|
37
|
+
spanKind, attributes,
|
|
38
|
+
// @ts-ignore
|
|
39
|
+
links) {
|
|
40
|
+
let isSampledIn = false;
|
|
41
|
+
if (this._sampleRate == 100) {
|
|
42
|
+
isSampledIn = true;
|
|
43
|
+
}
|
|
44
|
+
else if (this._sampleRate == 0) {
|
|
45
|
+
isSampledIn = false;
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
isSampledIn = this._getSamplingHashCode(traceId) < this._sampleRate;
|
|
49
|
+
}
|
|
50
|
+
// Add sample rate as span attribute
|
|
51
|
+
attributes = attributes || {};
|
|
52
|
+
attributes[AzureMonitorSampleRate] = this._sampleRate;
|
|
53
|
+
return isSampledIn
|
|
54
|
+
? { decision: SamplingDecision.RECORD_AND_SAMPLED, attributes: attributes }
|
|
55
|
+
: { decision: SamplingDecision.NOT_RECORD, attributes: attributes };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Return Sampler description
|
|
59
|
+
*/
|
|
60
|
+
toString() {
|
|
61
|
+
return `ApplicationInsightsSampler{${this._samplingRatio}}`;
|
|
62
|
+
}
|
|
63
|
+
_getSamplingHashCode(input) {
|
|
64
|
+
var csharpMin = -2147483648;
|
|
65
|
+
var csharpMax = 2147483647;
|
|
66
|
+
var hash = 5381;
|
|
67
|
+
if (!input) {
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
while (input.length < 8) {
|
|
71
|
+
input = input + input;
|
|
72
|
+
}
|
|
73
|
+
for (var i = 0; i < input.length; i++) {
|
|
74
|
+
// JS doesn't respond to integer overflow by wrapping around. Simulate it with bitwise operators ( | 0)
|
|
75
|
+
hash = ((((hash << 5) + hash) | 0) + input.charCodeAt(i)) | 0;
|
|
76
|
+
}
|
|
77
|
+
hash = hash <= csharpMin ? csharpMax : Math.abs(hash);
|
|
78
|
+
return (hash / csharpMax) * 100;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=sampling.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sampling.js","sourceRoot":"","sources":["../../src/sampling.ts"],"names":[],"mappings":"AAGA,OAAO,EAAW,gBAAgB,EAAkB,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAE/E;;;;;GAKG;AACH,MAAM,OAAO,0BAA0B;IAIrC,YAAY,gBAAwB,CAAC;QACnC,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;QACpC,IAAI,IAAI,CAAC,cAAc,GAAG,CAAC,EAAE;YAC3B,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;SACtE;QACD,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,CAAC;IAC3D,CAAC;IAED;;;;;;;;;;;;;OAaG;IACI,YAAY;IACjB,aAAa;IACb,OAAgB,EAChB,OAAe;IACf,aAAa;IACb,QAAgB;IAChB,aAAa;IACb,QAAkB,EAClB,UAAsB;IACtB,aAAa;IAC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AC,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SAC/D;QAED,IAAI,GAAG,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACtD,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,GAAG,GAAG,CAAC;IAClC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { Link, Attributes, SpanKind, Context } from \"@opentelemetry/api\";\nimport { Sampler, SamplingDecision, SamplingResult } from \"@opentelemetry/sdk-trace-base\";\nimport { AzureMonitorSampleRate } from \"./utils/constants/applicationinsights\";\n\n/**\n * ApplicationInsightsSampler is responsible for the following:\n * Implements same trace id hashing algorithm so that traces are sampled the same across multiple nodes\n * Adds item count to span attribute if span is sampled (needed for ingestion service)\n * @param samplingRatio - 0 to 1 value.\n */\nexport class ApplicationInsightsSampler implements Sampler {\n private readonly _sampleRate: number;\n private readonly _samplingRatio: number;\n\n constructor(samplingRatio: number = 1) {\n this._samplingRatio = samplingRatio;\n if (this._samplingRatio > 1) {\n throw new Error(\"Wrong sampling rate, data will not be sampled out\");\n }\n this._sampleRate = Math.round(this._samplingRatio * 100);\n }\n\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of SpanAttributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n public shouldSample(\n // @ts-ignore\n context: Context,\n traceId: string,\n // @ts-ignore\n spanName: string,\n // @ts-ignore\n spanKind: SpanKind,\n attributes: Attributes,\n // @ts-ignore\n links: Link[]\n ): SamplingResult {\n let isSampledIn = false;\n if (this._sampleRate == 100) {\n isSampledIn = true;\n } else if (this._sampleRate == 0) {\n isSampledIn = false;\n } else {\n isSampledIn = this._getSamplingHashCode(traceId) < this._sampleRate;\n }\n // Add sample rate as span attribute\n attributes = attributes || {};\n attributes[AzureMonitorSampleRate] = this._sampleRate;\n return isSampledIn\n ? { decision: SamplingDecision.RECORD_AND_SAMPLED, attributes: attributes }\n : { decision: SamplingDecision.NOT_RECORD, attributes: attributes };\n }\n\n /**\n * Return Sampler description\n */\n public toString(): string {\n return `ApplicationInsightsSampler{${this._samplingRatio}}`;\n }\n\n private _getSamplingHashCode(input: string): number {\n var csharpMin = -2147483648;\n var csharpMax = 2147483647;\n var hash = 5381;\n\n if (!input) {\n return 0;\n }\n\n while (input.length < 8) {\n input = input + input;\n }\n\n for (var i = 0; i < input.length; i++) {\n // JS doesn't respond to integer overflow by wrapping around. Simulate it with bitwise operators ( | 0)\n hash = ((((hash << 5) + hash) | 0) + input.charCodeAt(i)) | 0;\n }\n\n hash = hash <= csharpMin ? csharpMax : Math.abs(hash);\n return (hash / csharpMax) * 100;\n }\n}\n"]}
|
|
@@ -11,7 +11,9 @@ export function isRetriable(statusCode) {
|
|
|
11
11
|
statusCode === 408 || // Timeout
|
|
12
12
|
statusCode === 429 || // Too many requests
|
|
13
13
|
statusCode === 500 || // Server Error
|
|
14
|
-
statusCode ===
|
|
14
|
+
statusCode === 502 || // Bad Gateway
|
|
15
|
+
statusCode === 503 || // Server Unavailable
|
|
16
|
+
statusCode === 504 // Gateway Timeout
|
|
15
17
|
);
|
|
16
18
|
}
|
|
17
19
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"breezeUtils.js","sourceRoot":"","sources":["../../../src/utils/breezeUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAsBlC;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,UAAkB;IAC5C,OAAO,CACL,UAAU,KAAK,GAAG,IAAI,i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IAAI,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;IACtD,IAAI,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC;IAC5D,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAEzD,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IAC7C,GAAG,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IACvC,IAAI,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3C,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAE5C,OAAO,GAAG,QAAQ,GAAG,IAAI,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Breeze errors.\n * @internal\n */\nexport interface BreezeError {\n index: number;\n statusCode: number;\n message: string;\n}\n\n/**\n * Breeze response definition.\n * @internal\n */\nexport interface BreezeResponse {\n itemsReceived: number;\n itemsAccepted: number;\n errors: BreezeError[];\n}\n\n/**\n * Breeze retriable status codes.\n * @internal\n */\nexport function isRetriable(statusCode: number): boolean {\n return (\n statusCode === 206 || // Partial Accept\n statusCode === 401 || // Unauthorized\n statusCode === 403 || // Forbidden\n statusCode === 408 || // Timeout\n statusCode === 429 || // Too many requests\n statusCode === 500 || // Server Error\n statusCode === 502 || // Bad Gateway\n statusCode === 503 || // Server Unavailable\n statusCode === 504 // Gateway Timeout\n );\n}\n\n/**\n * Convert milliseconds to Breeze expected time.\n * @internal\n */\nexport function msToTimeSpan(ms: number): string {\n let totalms = ms;\n if (Number.isNaN(totalms) || totalms < 0 || !Number.isFinite(ms)) {\n totalms = 0;\n }\n\n let sec = ((totalms / 1000) % 60).toFixed(7).replace(/0{0,4}$/, \"\");\n let min = `${Math.floor(totalms / (1000 * 60)) % 60}`;\n let hour = `${Math.floor(totalms / (1000 * 60 * 60)) % 24}`;\n const days = Math.floor(totalms / (1000 * 60 * 60 * 24));\n\n sec = sec.indexOf(\".\") < 2 ? `0${sec}` : sec;\n min = min.length < 2 ? `0${min}` : min;\n hour = hour.length < 2 ? `0${hour}` : hour;\n const daysText = days > 0 ? `${days}.` : \"\";\n\n return `${daysText + hour}:${min}:${sec}`;\n}\n"]}
|
|
@@ -19,7 +19,7 @@ export const TIME_SINCE_ENQUEUED = "timeSinceEnqueued";
|
|
|
19
19
|
* AzureMonitorTraceExporter version.
|
|
20
20
|
* @internal
|
|
21
21
|
*/
|
|
22
|
-
export const packageVersion = "1.0.0-beta.
|
|
22
|
+
export const packageVersion = "1.0.0-beta.9";
|
|
23
23
|
export var DependencyTypes;
|
|
24
24
|
(function (DependencyTypes) {
|
|
25
25
|
DependencyTypes["InProc"] = "InProc";
|
|
@@ -28,4 +28,5 @@ export var DependencyTypes;
|
|
|
28
28
|
DependencyTypes["Http"] = "Http";
|
|
29
29
|
DependencyTypes["Grpc"] = "GRPC";
|
|
30
30
|
})(DependencyTypes || (DependencyTypes = {}));
|
|
31
|
+
export const AzureMonitorSampleRate = "_MS.sampleRate";
|
|
31
32
|
//# sourceMappingURL=applicationinsights.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"applicationinsights.js","sourceRoot":"","sources":["../../../../src/utils/constants/applicationinsights.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,WAAW,CAAC;AACpC;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,cAAc,CAAC;AAC5C;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AACvD;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,cAAc,CAAC;AAE7C,MAAM,CAAN,IAAY,eAMX;AAND,WAAY,eAAe;IACzB,oCAAiB,CAAA;IACjB,iDAA8B,CAAA;IAC9B,8BAAW,CAAA;IACX,gCAAa,CAAA;IACb,gCAAa,CAAA;AACf,CAAC,EANW,eAAe,KAAf,eAAe,QAM1B","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * AI MS Links.\n * @internal\n */\nexport const MS_LINKS = \"_MS.links\";\n/**\n * AI enqueued time attribute.\n * @internal\n */\nexport const ENQUEUED_TIME = \"enqueuedTime\";\n/**\n * AI time since enqueued attribute.\n * @internal\n */\nexport const TIME_SINCE_ENQUEUED = \"timeSinceEnqueued\";\n/**\n * AzureMonitorTraceExporter version.\n * @internal\n */\nexport const packageVersion = \"1.0.0-beta.
|
|
1
|
+
{"version":3,"file":"applicationinsights.js","sourceRoot":"","sources":["../../../../src/utils/constants/applicationinsights.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,WAAW,CAAC;AACpC;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,cAAc,CAAC;AAC5C;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AACvD;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,cAAc,CAAC;AAE7C,MAAM,CAAN,IAAY,eAMX;AAND,WAAY,eAAe;IACzB,oCAAiB,CAAA;IACjB,iDAA8B,CAAA;IAC9B,8BAAW,CAAA;IACX,gCAAa,CAAA;IACb,gCAAa,CAAA;AACf,CAAC,EANW,eAAe,KAAf,eAAe,QAM1B;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAG,gBAAgB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * AI MS Links.\n * @internal\n */\nexport const MS_LINKS = \"_MS.links\";\n/**\n * AI enqueued time attribute.\n * @internal\n */\nexport const ENQUEUED_TIME = \"enqueuedTime\";\n/**\n * AI time since enqueued attribute.\n * @internal\n */\nexport const TIME_SINCE_ENQUEUED = \"timeSinceEnqueued\";\n/**\n * AzureMonitorTraceExporter version.\n * @internal\n */\nexport const packageVersion = \"1.0.0-beta.9\";\n\nexport enum DependencyTypes {\n InProc = \"InProc\",\n QueueMessage = \"Queue Message\",\n Sql = \"SQL\",\n Http = \"Http\",\n Grpc = \"GRPC\",\n}\n\nexport const AzureMonitorSampleRate = \"_MS.sampleRate\";\n"]}
|
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
|
2
2
|
// Licensed under the MIT license.
|
|
3
|
-
import { DataPointType } from "@opentelemetry/sdk-metrics
|
|
3
|
+
import { DataPointType } from "@opentelemetry/sdk-metrics";
|
|
4
4
|
import { createTagsFromResource } from "./resourceUtils";
|
|
5
|
+
function createPropertiesFromMetricAttributes(attributes) {
|
|
6
|
+
const properties = {};
|
|
7
|
+
if (attributes) {
|
|
8
|
+
for (const key of Object.keys(attributes)) {
|
|
9
|
+
properties[key] = attributes[key];
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
return properties;
|
|
13
|
+
}
|
|
5
14
|
/**
|
|
6
15
|
* Metric to Azure envelope parsing.
|
|
7
16
|
* @internal
|
|
@@ -12,41 +21,46 @@ export function resourceMetricsToEnvelope(metrics, ikey) {
|
|
|
12
21
|
const instrumentationKey = ikey;
|
|
13
22
|
const tags = createTagsFromResource(metrics.resource);
|
|
14
23
|
metrics.scopeMetrics.forEach((scopeMetric) => {
|
|
15
|
-
let baseData = {
|
|
16
|
-
metrics: [],
|
|
17
|
-
version: 2,
|
|
18
|
-
};
|
|
19
24
|
scopeMetric.metrics.forEach((metric) => {
|
|
20
25
|
metric.dataPoints.forEach((dataPoint) => {
|
|
26
|
+
let baseData = {
|
|
27
|
+
metrics: [],
|
|
28
|
+
version: 2,
|
|
29
|
+
properties: {},
|
|
30
|
+
};
|
|
31
|
+
baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);
|
|
21
32
|
var metricDataPoint = {
|
|
22
33
|
name: metric.descriptor.name,
|
|
23
34
|
value: 0,
|
|
24
35
|
dataPointType: "Aggregation",
|
|
25
36
|
};
|
|
26
|
-
if (metric.dataPointType == DataPointType.
|
|
37
|
+
if (metric.dataPointType == DataPointType.SUM ||
|
|
38
|
+
metric.dataPointType == DataPointType.GAUGE) {
|
|
27
39
|
metricDataPoint.value = dataPoint.value;
|
|
28
40
|
metricDataPoint.count = 1;
|
|
29
41
|
}
|
|
30
42
|
else {
|
|
31
|
-
metricDataPoint.value = dataPoint.value.sum;
|
|
43
|
+
metricDataPoint.value = dataPoint.value.sum || 0;
|
|
32
44
|
metricDataPoint.count = dataPoint.value.count;
|
|
45
|
+
metricDataPoint.max = dataPoint.value.max;
|
|
46
|
+
metricDataPoint.min = dataPoint.value.min;
|
|
33
47
|
}
|
|
34
48
|
baseData.metrics.push(metricDataPoint);
|
|
49
|
+
let envelope = {
|
|
50
|
+
name: "Microsoft.ApplicationInsights.Metric",
|
|
51
|
+
time: time,
|
|
52
|
+
sampleRate: 100,
|
|
53
|
+
instrumentationKey: instrumentationKey,
|
|
54
|
+
tags: tags,
|
|
55
|
+
version: 1,
|
|
56
|
+
data: {
|
|
57
|
+
baseType: "MetricData",
|
|
58
|
+
baseData: Object.assign({}, baseData),
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
envelopes.push(envelope);
|
|
35
62
|
});
|
|
36
63
|
});
|
|
37
|
-
let envelope = {
|
|
38
|
-
name: "Microsoft.ApplicationInsights.Metric",
|
|
39
|
-
time: time,
|
|
40
|
-
sampleRate: 100,
|
|
41
|
-
instrumentationKey: instrumentationKey,
|
|
42
|
-
tags: tags,
|
|
43
|
-
version: 1,
|
|
44
|
-
data: {
|
|
45
|
-
baseType: "MetricData",
|
|
46
|
-
baseData: Object.assign({}, baseData),
|
|
47
|
-
},
|
|
48
|
-
};
|
|
49
|
-
envelopes.push(envelope);
|
|
50
64
|
});
|
|
51
65
|
return envelopes;
|
|
52
66
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metricUtils.js","sourceRoot":"","sources":["../../../src/utils/metricUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;
|
|
1
|
+
{"version":3,"file":"metricUtils.js","sourceRoot":"","sources":["../../../src/utils/metricUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,aAAa,EAA8B,MAAM,4BAA4B,CAAC;AAEvF,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAEzD,SAAS,oCAAoC,CAAC,UAA6B;IAGzE,MAAM,UAAU,GAAuC,EAAE,CAAC;IAC1D,IAAI,UAAU,EAAE;QACd,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE;YACzC,UAAU,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,GAAG,CAAW,CAAC;SAC7C;KACF;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAwB,EAAE,IAAY;IAC9E,IAAI,SAAS,GAAe,EAAE,CAAC;IAC/B,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;IACxB,MAAM,kBAAkB,GAAG,IAAI,CAAC;IAChC,MAAM,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AAI,EAAE,IAAI;oBACV,UAAU,EAAE,GAAG;oBACf,kBAAkB,EAAE,kBAAkB;oBACtC,IAAI,EAAE,IAAI;oBACV,OAAO,EAAE,CAAC;oBACV,IAAI,EAAE;wBACJ,QAAQ,EAAE,YAAY;wBACtB,QAAQ,oBACH,QAAQ,CACZ;qBACF;iBACF,CAAC;gBACF,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC3B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MetricAttributes } from \"@opentelemetry/api-metrics\";\nimport { DataPointType, Histogram, ResourceMetrics } from \"@opentelemetry/sdk-metrics\";\nimport { TelemetryItem as Envelope, MetricsData, MetricDataPoint } from \"../generated\";\nimport { createTagsFromResource } from \"./resourceUtils\";\n\nfunction createPropertiesFromMetricAttributes(attributes?: MetricAttributes): {\n [propertyName: string]: string;\n} {\n const properties: { [propertyName: string]: string } = {};\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n properties[key] = attributes[key] as string;\n }\n }\n return properties;\n}\n\n/**\n * Metric to Azure envelope parsing.\n * @internal\n */\nexport function resourceMetricsToEnvelope(metrics: ResourceMetrics, ikey: string): Envelope[] {\n let envelopes: Envelope[] = [];\n const time = new Date();\n const instrumentationKey = ikey;\n const tags = createTagsFromResource(metrics.resource);\n\n metrics.scopeMetrics.forEach((scopeMetric) => {\n scopeMetric.metrics.forEach((metric) => {\n metric.dataPoints.forEach((dataPoint) => {\n let baseData: MetricsData = {\n metrics: [],\n version: 2,\n properties: {},\n };\n baseData.properties = createPropertiesFromMetricAttributes(dataPoint.attributes);\n var metricDataPoint: MetricDataPoint = {\n name: metric.descriptor.name,\n value: 0,\n dataPointType: \"Aggregation\",\n };\n if (\n metric.dataPointType == DataPointType.SUM ||\n metric.dataPointType == DataPointType.GAUGE\n ) {\n metricDataPoint.value = dataPoint.value as number;\n metricDataPoint.count = 1;\n } else {\n metricDataPoint.value = (dataPoint.value as Histogram).sum || 0;\n metricDataPoint.count = (dataPoint.value as Histogram).count;\n metricDataPoint.max = (dataPoint.value as Histogram).max;\n metricDataPoint.min = (dataPoint.value as Histogram).min;\n }\n baseData.metrics.push(metricDataPoint);\n let envelope: Envelope = {\n name: \"Microsoft.ApplicationInsights.Metric\",\n time: time,\n sampleRate: 100, // Metrics are never sampled\n instrumentationKey: instrumentationKey,\n tags: tags,\n version: 1,\n data: {\n baseType: \"MetricData\",\n baseData: {\n ...baseData,\n },\n },\n };\n envelopes.push(envelope);\n });\n });\n });\n\n return envelopes;\n}\n"]}
|
|
@@ -7,10 +7,10 @@ import { SemanticAttributes, DbSystemValues } from "@opentelemetry/semantic-conv
|
|
|
7
7
|
import { createTagsFromResource } from "./resourceUtils";
|
|
8
8
|
import { msToTimeSpan } from "./breezeUtils";
|
|
9
9
|
import { parseEventHubSpan } from "./eventhub";
|
|
10
|
-
import { DependencyTypes, MS_LINKS } from "./constants/applicationinsights";
|
|
10
|
+
import { AzureMonitorSampleRate, DependencyTypes, MS_LINKS } from "./constants/applicationinsights";
|
|
11
11
|
import { AzNamespace, MicrosoftEventHub } from "./constants/span/azAttributes";
|
|
12
12
|
import { KnownContextTagKeys, } from "../generated";
|
|
13
|
-
function
|
|
13
|
+
function createTagsFromSpan(span) {
|
|
14
14
|
const tags = createTagsFromResource(span.resource);
|
|
15
15
|
tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;
|
|
16
16
|
if (span.parentSpanId) {
|
|
@@ -21,10 +21,6 @@ function createGenericTagsFromSpan(span) {
|
|
|
21
21
|
// TODO: Not exposed in Swagger, need to update def
|
|
22
22
|
tags["ai.user.userAgent"] = String(httpUserAgent);
|
|
23
23
|
}
|
|
24
|
-
return tags;
|
|
25
|
-
}
|
|
26
|
-
function createTagsFromSpan(span) {
|
|
27
|
-
const tags = createGenericTagsFromSpan(span);
|
|
28
24
|
if (span.kind === SpanKind.SERVER) {
|
|
29
25
|
const httpMethod = span.attributes[SemanticAttributes.HTTP_METHOD];
|
|
30
26
|
const httpClientIp = span.attributes[SemanticAttributes.HTTP_CLIENT_IP];
|
|
@@ -75,7 +71,8 @@ function createPropertiesFromSpanAttributes(attributes) {
|
|
|
75
71
|
key.startsWith("exception.") ||
|
|
76
72
|
key.startsWith("thread.") ||
|
|
77
73
|
key.startsWith("faas.") ||
|
|
78
|
-
key.startsWith("code.")
|
|
74
|
+
key.startsWith("code.") ||
|
|
75
|
+
key.startsWith("_MS."))) {
|
|
79
76
|
properties[key] = attributes[key];
|
|
80
77
|
}
|
|
81
78
|
}
|
|
@@ -302,7 +299,6 @@ function createRequestData(span) {
|
|
|
302
299
|
export function readableSpanToEnvelope(span, ikey) {
|
|
303
300
|
let name;
|
|
304
301
|
let baseType;
|
|
305
|
-
const sampleRate = 100;
|
|
306
302
|
let baseData;
|
|
307
303
|
const time = new Date(hrTimeToMilliseconds(span.startTime));
|
|
308
304
|
const instrumentationKey = ikey;
|
|
@@ -328,6 +324,10 @@ export function readableSpanToEnvelope(span, ikey) {
|
|
|
328
324
|
diag.error(`Unsupported span kind ${span.kind}`);
|
|
329
325
|
throw new Error(`Unsupported span kind ${span.kind}`);
|
|
330
326
|
}
|
|
327
|
+
let sampleRate = 100;
|
|
328
|
+
if (span.attributes[AzureMonitorSampleRate]) {
|
|
329
|
+
sampleRate = Number(span.attributes[AzureMonitorSampleRate]);
|
|
330
|
+
}
|
|
331
331
|
// Azure SDK
|
|
332
332
|
if (span.attributes[AzNamespace]) {
|
|
333
333
|
if (span.kind === SpanKind.INTERNAL) {
|
|
@@ -359,14 +359,20 @@ export function spanEventsToEnvelopes(span, ikey) {
|
|
|
359
359
|
let envelopes = [];
|
|
360
360
|
if (span.events) {
|
|
361
361
|
span.events.forEach((event) => {
|
|
362
|
+
var _a;
|
|
362
363
|
let baseType;
|
|
363
|
-
const sampleRate = 100;
|
|
364
364
|
let time = new Date(hrTimeToMilliseconds(event.time));
|
|
365
365
|
let name = "";
|
|
366
366
|
let baseData;
|
|
367
367
|
const properties = createPropertiesFromSpanAttributes(event.attributes);
|
|
368
|
-
|
|
369
|
-
|
|
368
|
+
let tags = createTagsFromResource(span.resource);
|
|
369
|
+
tags[KnownContextTagKeys.AiOperationId] = span.spanContext().traceId;
|
|
370
|
+
let spanId = (_a = span.spanContext()) === null || _a === void 0 ? void 0 : _a.spanId;
|
|
371
|
+
if (spanId) {
|
|
372
|
+
tags[KnownContextTagKeys.AiOperationParentId] = spanId;
|
|
373
|
+
}
|
|
374
|
+
// Only generate exception telemetry for incoming requests
|
|
375
|
+
if (event.name == "exception" && span.kind == SpanKind.SERVER) {
|
|
370
376
|
name = "Microsoft.ApplicationInsights.Exception";
|
|
371
377
|
baseType = "ExceptionData";
|
|
372
378
|
let typeName = "";
|
|
@@ -411,6 +417,10 @@ export function spanEventsToEnvelopes(span, ikey) {
|
|
|
411
417
|
};
|
|
412
418
|
baseData = messageData;
|
|
413
419
|
}
|
|
420
|
+
let sampleRate = 100;
|
|
421
|
+
if (span.attributes[AzureMonitorSampleRate]) {
|
|
422
|
+
sampleRate = Number(span.attributes[AzureMonitorSampleRate]);
|
|
423
|
+
}
|
|
414
424
|
let env = {
|
|
415
425
|
name: name,
|
|
416
426
|
time: time,
|