@azure/monitor-opentelemetry-exporter 1.0.0-beta.35 → 1.0.0-beta.36

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 (46) hide show
  1. package/dist/commonjs/export/statsbeat/customerSDKStats.d.ts +2 -2
  2. package/dist/commonjs/export/statsbeat/customerSDKStats.d.ts.map +1 -1
  3. package/dist/commonjs/export/statsbeat/customerSDKStats.js +11 -9
  4. package/dist/commonjs/export/statsbeat/customerSDKStats.js.map +1 -1
  5. package/dist/commonjs/export/statsbeat/statsbeatExporter.d.ts +5 -0
  6. package/dist/commonjs/export/statsbeat/statsbeatExporter.d.ts.map +1 -1
  7. package/dist/commonjs/export/statsbeat/statsbeatExporter.js +19 -5
  8. package/dist/commonjs/export/statsbeat/statsbeatExporter.js.map +1 -1
  9. package/dist/commonjs/generated/applicationInsightsClient.js +1 -1
  10. package/dist/commonjs/generated/applicationInsightsClient.js.map +1 -1
  11. package/dist/commonjs/platform/nodejs/baseSender.d.ts.map +1 -1
  12. package/dist/commonjs/platform/nodejs/baseSender.js +18 -7
  13. package/dist/commonjs/platform/nodejs/baseSender.js.map +1 -1
  14. package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.d.ts +15 -0
  15. package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.d.ts.map +1 -1
  16. package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.js +65 -2
  17. package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.js.map +1 -1
  18. package/dist/commonjs/tsdoc-metadata.json +1 -1
  19. package/dist/commonjs/utils/constants/applicationinsights.d.ts +1 -1
  20. package/dist/commonjs/utils/constants/applicationinsights.js +1 -1
  21. package/dist/commonjs/utils/constants/applicationinsights.js.map +1 -1
  22. package/dist/commonjs/utils/logUtils.js +2 -2
  23. package/dist/commonjs/utils/logUtils.js.map +1 -1
  24. package/dist/esm/export/statsbeat/customerSDKStats.d.ts +2 -2
  25. package/dist/esm/export/statsbeat/customerSDKStats.d.ts.map +1 -1
  26. package/dist/esm/export/statsbeat/customerSDKStats.js +11 -9
  27. package/dist/esm/export/statsbeat/customerSDKStats.js.map +1 -1
  28. package/dist/esm/export/statsbeat/statsbeatExporter.d.ts +5 -0
  29. package/dist/esm/export/statsbeat/statsbeatExporter.d.ts.map +1 -1
  30. package/dist/esm/export/statsbeat/statsbeatExporter.js +19 -5
  31. package/dist/esm/export/statsbeat/statsbeatExporter.js.map +1 -1
  32. package/dist/esm/generated/applicationInsightsClient.js +1 -1
  33. package/dist/esm/generated/applicationInsightsClient.js.map +1 -1
  34. package/dist/esm/platform/nodejs/baseSender.d.ts.map +1 -1
  35. package/dist/esm/platform/nodejs/baseSender.js +18 -7
  36. package/dist/esm/platform/nodejs/baseSender.js.map +1 -1
  37. package/dist/esm/platform/nodejs/persist/fileSystemPersist.d.ts +15 -0
  38. package/dist/esm/platform/nodejs/persist/fileSystemPersist.d.ts.map +1 -1
  39. package/dist/esm/platform/nodejs/persist/fileSystemPersist.js +66 -4
  40. package/dist/esm/platform/nodejs/persist/fileSystemPersist.js.map +1 -1
  41. package/dist/esm/utils/constants/applicationinsights.d.ts +1 -1
  42. package/dist/esm/utils/constants/applicationinsights.js +1 -1
  43. package/dist/esm/utils/constants/applicationinsights.js.map +1 -1
  44. package/dist/esm/utils/logUtils.js +2 -2
  45. package/dist/esm/utils/logUtils.js.map +1 -1
  46. package/package.json +16 -12
@@ -1,7 +1,8 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
- import { tmpdir } from "node:os";
4
- import { basename, join } from "node:path";
3
+ import { tmpdir, userInfo } from "node:os";
4
+ import { basename, join, dirname } from "node:path";
5
+ import { createHash } from "node:crypto";
5
6
  import { diag } from "@opentelemetry/api";
6
7
  import { FileAccessControl } from "./fileAccessControl.js";
7
8
  import { confirmDirExists, getShallowDirectorySize } from "./fileSystemHelpers.js";
@@ -14,7 +15,7 @@ import { DropCode, ExceptionType } from "../../../export/statsbeat/types.js";
14
15
  export class FileSystemPersist {
15
16
  _options;
16
17
  _customerSDKStatsMetrics;
17
- static TEMPDIR_PREFIX = "ot-azure-exporter-";
18
+ static TEMPDIR_PREFIX = "opentelemetry-nodejs-";
18
19
  static FILENAME_SUFFIX = ".ai.json";
19
20
  fileRetemptionPeriod = 2 * 24 * 60 * 60 * 1000; // 2 days
20
21
  cleanupTimeOut = 60 * 60 * 1000; // 1 hour
@@ -42,7 +43,7 @@ export class FileSystemPersist {
42
43
  diag.error(`No instrumentation key was provided to FileSystemPersister. Files will not be persisted`);
43
44
  }
44
45
  if (this._enabled) {
45
- this._tempDirectory = join(this._options?.storageDirectory || tmpdir(), "Microsoft", "AzureMonitor", FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey);
46
+ this._tempDirectory = getStorageDirectory(this._instrumentationKey, this._options?.storageDirectory);
46
47
  // Starts file cleanup task
47
48
  if (!this._fileCleanupTimer) {
48
49
  this._fileCleanupTimer = setTimeout(() => {
@@ -198,4 +199,65 @@ export class FileSystemPersist {
198
199
  }
199
200
  }
200
201
  }
202
+ /**
203
+ * Return the deterministic local storage path for a given instrumentation key.
204
+ *
205
+ * On shared Linux hosts the first user to create `/tmp/Microsoft/AzureMonitor` can
206
+ * block others because the directory inherits that user's `umask`. This is avoided by
207
+ * inserting a hash of the instrumentation key, user name, process name, and
208
+ * application directory, giving each user their own subdirectory, e.g.
209
+ * `/tmp/Microsoft-AzureMonitor-1234...../opentelemetry-nodejs-<ikey>`.
210
+ *
211
+ * @param instrumentationKey - Application Insights instrumentation key.
212
+ * @param storageDirectory - Optional custom storage directory path. If not provided, system temp directory is used.
213
+ * @returns Absolute path to the storage directory.
214
+ * @internal
215
+ */
216
+ export function getStorageDirectory(instrumentationKey, storageDirectory) {
217
+ let userSegment;
218
+ let processName;
219
+ let applicationDirectory;
220
+ try {
221
+ const user = userInfo();
222
+ userSegment = user.username;
223
+ }
224
+ catch (error) {
225
+ userSegment = "";
226
+ }
227
+ if (process.title.length > 0) {
228
+ processName = process.title;
229
+ }
230
+ else {
231
+ processName = "";
232
+ }
233
+ const applicationDir = dirname(process.cwd() || process.argv[1]);
234
+ if (applicationDir) {
235
+ applicationDirectory = applicationDir;
236
+ }
237
+ else {
238
+ applicationDirectory = "";
239
+ }
240
+ const hash_input = `${instrumentationKey}|${userSegment}|${processName}|${applicationDirectory}`;
241
+ let subDirectory;
242
+ try {
243
+ subDirectory = createHash("sha256").update(hash_input).digest("hex");
244
+ }
245
+ catch (error) {
246
+ let hash = 5381;
247
+ for (let i = 0; i < hash_input.length; i++) {
248
+ const char = hash_input.charCodeAt(i);
249
+ hash = (hash << 5) + hash + char;
250
+ hash = hash & hash;
251
+ }
252
+ subDirectory = Math.abs(hash).toString(16);
253
+ }
254
+ let sharedRoot;
255
+ if (storageDirectory) {
256
+ sharedRoot = storageDirectory;
257
+ }
258
+ else {
259
+ sharedRoot = tmpdir();
260
+ }
261
+ return join(sharedRoot, "Microsoft-AzureMonitor-" + subDirectory, FileSystemPersist.TEMPDIR_PREFIX + instrumentationKey);
262
+ }
201
263
  //# sourceMappingURL=fileSystemPersist.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fileSystemPersist.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAEnF,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE9E,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AQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,iBAAiB,CAAC,eAAe,CAAC,CACxD,CAAC;gBACF,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBACvB,OAAO,KAAK,CAAC;gBACf,CAAC;qBAAM,CAAC;oBACN,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,CAAC;4BACZ,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;4BACjD,MAAM,MAAM,CAAC,QAAQ,CAAC,CAAC;wBACzB,CAAC;oBACH,CAAC,CAAC,CAAC;oBACH,OAAO,IAAI,CAAC;gBACd,CAAC;YACH,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { tmpdir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport { diag } from \"@opentelemetry/api\";\nimport type { PersistentStorage } from \"../../../types.js\";\nimport { FileAccessControl } from \"./fileAccessControl.js\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers.js\";\nimport type { AzureMonitorExporterOptions } from \"../../../config.js\";\nimport { readdir, readFile, stat, unlink, writeFile } from \"node:fs/promises\";\nimport type { CustomerSDKStatsMetrics } from \"../../../export/statsbeat/customerSDKStats.js\";\nimport { DropCode, ExceptionType } from \"../../../export/statsbeat/types.js\";\nimport type { TelemetryItem as Envelope } from \"../../../generated/index.js\";\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 = 2 * 24 * 60 * 60 * 1000; // 2 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.Timeout | null = null;\n private _instrumentationKey: string;\n\n constructor(\n instrumentationKey: string,\n private _options?: AzureMonitorExporterOptions,\n private _customerSDKStatsMetrics?: CustomerSDKStatsMetrics,\n ) {\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 = join(\n this._options?.storageDirectory || 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), value as Envelope[]);\n }\n // Only return a false promise if the SDK isn't set to disable offline storage\n if (!this._options?.disableOfflineStorage) {\n return new Promise((resolve) => {\n resolve(false);\n });\n }\n return new Promise((resolve) => {\n resolve(true);\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 stat(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdir(this._tempDirectory);\n const files = origFiles.filter((f) =>\n 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 = join(this._tempDirectory, firstFile);\n const payload = await readFile(filePath);\n // delete the file first to prevent double sending\n await unlink(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 /**\n * Stores telemetry data to disk.\n * @param payload - The telemetry data to store.\n * @param envelopeLength -The length of the telemetry envelope.\n * @returns A promise that resolves to true if the data was stored successfully, false otherwise.\n */\n private async _storeToDisk(payload: string, envelopes: Envelope[]): Promise<boolean> {\n try {\n await confirmDirExists(this._tempDirectory);\n } catch (error: any) {\n // Check if error is due to permission/readonly issues\n if (error?.code === \"EACCES\" || error?.code === \"EPERM\") {\n this._customerSDKStatsMetrics?.countDroppedItems(envelopes, DropCode.CLIENT_READONLY);\n diag.warn(\n `Permission denied while checking/creating directory: ${this._tempDirectory}`,\n error?.message,\n );\n } else {\n diag.warn(`Error while checking/creating directory: `, error && error.message);\n }\n return false;\n }\n\n try {\n const size = await getShallowDirectorySize(this._tempDirectory);\n if (size > this.maxBytesOnDisk) {\n // If the directory size exceeds the max limit, we send customer SDK Stats and warn the user\n this._customerSDKStatsMetrics?.countDroppedItems(\n envelopes,\n DropCode.CLIENT_PERSISTENCE_CAPACITY,\n );\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 = 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 writeFile(fileFullPath, payload, { mode: 0o600 });\n } catch (writeError: any) {\n // If the envelopes cannot be written to disk, we send customer SDK Stats and warn the user\n this._customerSDKStatsMetrics?.countDroppedItems(\n envelopes,\n DropCode.CLIENT_EXCEPTION,\n writeError?.message,\n ExceptionType.STORAGE_EXCEPTION,\n );\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 stat(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdir(this._tempDirectory);\n const files = origFiles.filter((f) =>\n 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 = join(this._tempDirectory, file);\n await unlink(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":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CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,IAAI,GAAG,IAAI,CAAC;QAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC3C,MAAM,IAAI,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YACtC,IAAI,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;YACjC,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;QACrB,CAAC;QACD,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC7C,CAAC;IAED,IAAI,UAAkB,CAAC;IACvB,IAAI,gBAAgB,EAAE,CAAC;QACrB,UAAU,GAAG,gBAAgB,CAAC;IAChC,CAAC;SAAM,CAAC;QACN,UAAU,GAAG,MAAM,EAAE,CAAC;IACxB,CAAC;IACD,OAAO,IAAI,CACT,UAAU,EACV,yBAAyB,GAAG,YAAY,EACxC,iBAAiB,CAAC,cAAc,GAAG,kBAAkB,CACtD,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { tmpdir, userInfo } from \"node:os\";\nimport { basename, join, dirname } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { diag } from \"@opentelemetry/api\";\nimport type { PersistentStorage } from \"../../../types.js\";\nimport { FileAccessControl } from \"./fileAccessControl.js\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers.js\";\nimport type { AzureMonitorExporterOptions } from \"../../../config.js\";\nimport { readdir, readFile, stat, unlink, writeFile } from \"node:fs/promises\";\nimport type { CustomerSDKStatsMetrics } from \"../../../export/statsbeat/customerSDKStats.js\";\nimport { DropCode, ExceptionType } from \"../../../export/statsbeat/types.js\";\nimport type { TelemetryItem as Envelope } from \"../../../generated/index.js\";\n\n/**\n * File system persist class.\n * @internal\n */\nexport class FileSystemPersist implements PersistentStorage {\n static TEMPDIR_PREFIX = \"opentelemetry-nodejs-\";\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 2 * 24 * 60 * 60 * 1000; // 2 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.Timeout | null = null;\n private _instrumentationKey: string;\n\n constructor(\n instrumentationKey: string,\n private _options?: AzureMonitorExporterOptions,\n private _customerSDKStatsMetrics?: CustomerSDKStatsMetrics,\n ) {\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 = getStorageDirectory(\n this._instrumentationKey,\n this._options?.storageDirectory,\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), value as Envelope[]);\n }\n // Only return a false promise if the SDK isn't set to disable offline storage\n if (!this._options?.disableOfflineStorage) {\n return new Promise((resolve) => {\n resolve(false);\n });\n }\n return new Promise((resolve) => {\n resolve(true);\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 stat(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdir(this._tempDirectory);\n const files = origFiles.filter((f) =>\n 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 = join(this._tempDirectory, firstFile);\n const payload = await readFile(filePath);\n // delete the file first to prevent double sending\n await unlink(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 /**\n * Stores telemetry data to disk.\n * @param payload - The telemetry data to store.\n * @param envelopeLength -The length of the telemetry envelope.\n * @returns A promise that resolves to true if the data was stored successfully, false otherwise.\n */\n private async _storeToDisk(payload: string, envelopes: Envelope[]): Promise<boolean> {\n try {\n await confirmDirExists(this._tempDirectory);\n } catch (error: any) {\n // Check if error is due to permission/readonly issues\n if (error?.code === \"EACCES\" || error?.code === \"EPERM\") {\n this._customerSDKStatsMetrics?.countDroppedItems(envelopes, DropCode.CLIENT_READONLY);\n diag.warn(\n `Permission denied while checking/creating directory: ${this._tempDirectory}`,\n error?.message,\n );\n } else {\n diag.warn(`Error while checking/creating directory: `, error && error.message);\n }\n return false;\n }\n\n try {\n const size = await getShallowDirectorySize(this._tempDirectory);\n if (size > this.maxBytesOnDisk) {\n // If the directory size exceeds the max limit, we send customer SDK Stats and warn the user\n this._customerSDKStatsMetrics?.countDroppedItems(\n envelopes,\n DropCode.CLIENT_PERSISTENCE_CAPACITY,\n );\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 = 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 writeFile(fileFullPath, payload, { mode: 0o600 });\n } catch (writeError: any) {\n // If the envelopes cannot be written to disk, we send customer SDK Stats and warn the user\n this._customerSDKStatsMetrics?.countDroppedItems(\n envelopes,\n DropCode.CLIENT_EXCEPTION,\n writeError?.message,\n ExceptionType.STORAGE_EXCEPTION,\n );\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 stat(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdir(this._tempDirectory);\n const files = origFiles.filter((f) =>\n 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 = join(this._tempDirectory, file);\n await unlink(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\n/**\n * Return the deterministic local storage path for a given instrumentation key.\n *\n * On shared Linux hosts the first user to create `/tmp/Microsoft/AzureMonitor` can\n * block others because the directory inherits that user's `umask`. This is avoided by\n * inserting a hash of the instrumentation key, user name, process name, and\n * application directory, giving each user their own subdirectory, e.g.\n * `/tmp/Microsoft-AzureMonitor-1234...../opentelemetry-nodejs-<ikey>`.\n *\n * @param instrumentationKey - Application Insights instrumentation key.\n * @param storageDirectory - Optional custom storage directory path. If not provided, system temp directory is used.\n * @returns Absolute path to the storage directory.\n * @internal\n */\nexport function getStorageDirectory(\n instrumentationKey: string,\n storageDirectory: string | undefined,\n): string {\n let userSegment: string;\n let processName: string;\n let applicationDirectory: string;\n try {\n const user = userInfo();\n userSegment = user.username;\n } catch (error) {\n userSegment = \"\";\n }\n if (process.title.length > 0) {\n processName = process.title;\n } else {\n processName = \"\";\n }\n const applicationDir = dirname(process.cwd() || process.argv[1]);\n if (applicationDir) {\n applicationDirectory = applicationDir;\n } else {\n applicationDirectory = \"\";\n }\n const hash_input = `${instrumentationKey}|${userSegment}|${processName}|${applicationDirectory}`;\n\n let subDirectory: string;\n try {\n subDirectory = createHash(\"sha256\").update(hash_input).digest(\"hex\");\n } catch (error) {\n let hash = 5381;\n for (let i = 0; i < hash_input.length; i++) {\n const char = hash_input.charCodeAt(i);\n hash = (hash << 5) + hash + char;\n hash = hash & hash;\n }\n subDirectory = Math.abs(hash).toString(16);\n }\n\n let sharedRoot: string;\n if (storageDirectory) {\n sharedRoot = storageDirectory;\n } else {\n sharedRoot = tmpdir();\n }\n return join(\n sharedRoot,\n \"Microsoft-AzureMonitor-\" + subDirectory,\n FileSystemPersist.TEMPDIR_PREFIX + instrumentationKey,\n );\n}\n"]}
@@ -17,7 +17,7 @@ export declare const TIME_SINCE_ENQUEUED = "timeSinceEnqueued";
17
17
  * AzureMonitorTraceExporter version.
18
18
  * @internal
19
19
  */
20
- export declare const packageVersion = "1.0.0-beta.35";
20
+ export declare const packageVersion = "1.0.0-beta.36";
21
21
  export declare enum DependencyTypes {
22
22
  InProc = "InProc",
23
23
  QueueMessage = "Queue Message",
@@ -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.35";
22
+ export const packageVersion = "1.0.0-beta.36";
23
23
  export var DependencyTypes;
24
24
  (function (DependencyTypes) {
25
25
  DependencyTypes["InProc"] = "InProc";
@@ -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,eAAe,CAAC;AAE9C,MAAM,CAAN,IAAY,eAOX;AAPD,WAAY,eAAe;IACzB,oCAAiB,CAAA;IACjB,iDAA8B,CAAA;IAC9B,8BAAW,CAAA;IACX,gCAAa,CAAA;IACb,gCAAa,CAAA;IACb,sCAAmB,CAAA;AACrB,CAAC,EAPW,eAAe,KAAf,eAAe,QAO1B;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAG,uBAAuB,CAAC;AAC9D,MAAM,CAAC,MAAM,2BAA2B,GAAG,cAAc,CAAC;AAC1D,MAAM,CAAC,MAAM,kCAAkC,GAAG,6BAA6B,CAAC;AAChF,MAAM,CAAC,MAAM,iBAAiB,GAAG,qBAAqB,CAAC;AAEvD,MAAM,CAAC,MAAM,8BAA8B,GAAG,uCAAuC,CAAC;AACtF,MAAM,CAAC,MAAM,gCAAgC,GAAG,yCAAyC,CAAC;AAC1F,MAAM,CAAC,MAAM,+BAA+B,GAAG,wCAAwC,CAAC;AACxF,MAAM,CAAC,MAAM,mCAAmC,GAAG,4CAA4C,CAAC;AAChG,MAAM,CAAC,MAAM,4BAA4B,GAAG,qCAAqC,CAAC;AAElF,MAAM,CAAC,MAAM,kCAAkC,GAAG,aAAa,CAAC;AAChE,MAAM,CAAC,MAAM,oCAAoC,GAAG,eAAe,CAAC;AACpE,MAAM,CAAC,MAAM,mCAAmC,GAAG,cAAc,CAAC;AAClE,MAAM,CAAC,MAAM,uCAAuC,GAAG,kBAAkB,CAAC;AAC1E,MAAM,CAAC,MAAM,gCAAgC,GAAG,WAAW,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.35\";\n\nexport enum DependencyTypes {\n InProc = \"InProc\",\n QueueMessage = \"Queue Message\",\n Sql = \"SQL\",\n Http = \"Http\",\n Grpc = \"GRPC\",\n Wcf = \"WCF Service\",\n}\n\nexport const AzureMonitorSampleRate = \"microsoft.sample_rate\";\nexport const ApplicationInsightsBaseType = \"_MS.baseType\";\nexport const ApplicationInsightsCustomEventName = \"microsoft.custom_event.name\";\nexport const MicrosoftClientIp = \"microsoft.client.ip\";\n\nexport const ApplicationInsightsMessageName = \"Microsoft.ApplicationInsights.Message\";\nexport const ApplicationInsightsExceptionName = \"Microsoft.ApplicationInsights.Exception\";\nexport const ApplicationInsightsPageViewName = \"Microsoft.ApplicationInsights.PageView\";\nexport const ApplicationInsightsAvailabilityName = \"Microsoft.ApplicationInsights.Availability\";\nexport const ApplicationInsightsEventName = \"Microsoft.ApplicationInsights.Event\";\n\nexport const ApplicationInsightsMessageBaseType = \"MessageData\";\nexport const ApplicationInsightsExceptionBaseType = \"ExceptionData\";\nexport const ApplicationInsightsPageViewBaseType = \"PageViewData\";\nexport const ApplicationInsightsAvailabilityBaseType = \"AvailabilityData\";\nexport const ApplicationInsightsEventBaseType = \"EventData\";\n"]}
1
+ {"version":3,"file":"appl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,CAAC;AAC1E,MAAM,CAAC,MAAM,gCAAgC,GAAG,WAAW,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.36\";\n\nexport enum DependencyTypes {\n InProc = \"InProc\",\n QueueMessage = \"Queue Message\",\n Sql = \"SQL\",\n Http = \"Http\",\n Grpc = \"GRPC\",\n Wcf = \"WCF Service\",\n}\n\nexport const AzureMonitorSampleRate = \"microsoft.sample_rate\";\nexport const ApplicationInsightsBaseType = \"_MS.baseType\";\nexport const ApplicationInsightsCustomEventName = \"microsoft.custom_event.name\";\nexport const MicrosoftClientIp = \"microsoft.client.ip\";\n\nexport const ApplicationInsightsMessageName = \"Microsoft.ApplicationInsights.Message\";\nexport const ApplicationInsightsExceptionName = \"Microsoft.ApplicationInsights.Exception\";\nexport const ApplicationInsightsPageViewName = \"Microsoft.ApplicationInsights.PageView\";\nexport const ApplicationInsightsAvailabilityName = \"Microsoft.ApplicationInsights.Availability\";\nexport const ApplicationInsightsEventName = \"Microsoft.ApplicationInsights.Event\";\n\nexport const ApplicationInsightsMessageBaseType = \"MessageData\";\nexport const ApplicationInsightsExceptionBaseType = \"ExceptionData\";\nexport const ApplicationInsightsPageViewBaseType = \"PageViewData\";\nexport const ApplicationInsightsAvailabilityBaseType = \"AvailabilityData\";\nexport const ApplicationInsightsEventBaseType = \"EventData\";\n"]}
@@ -58,7 +58,7 @@ export function logToEnvelope(log, ikey) {
58
58
  name = ApplicationInsightsMessageName;
59
59
  baseType = ApplicationInsightsMessageBaseType;
60
60
  const messageData = {
61
- message: String(log.body),
61
+ message: serializeAttribute(log.body),
62
62
  severityLevel: String(getSeverity(log.severityNumber)),
63
63
  version: 2,
64
64
  };
@@ -226,7 +226,7 @@ function getLegacyApplicationInsightsBaseData(log) {
226
226
  break;
227
227
  }
228
228
  if (typeof baseData?.message === "object") {
229
- baseData.message = JSON.stringify(baseData.message);
229
+ baseData.message = serializeAttribute(baseData.message);
230
230
  }
231
231
  }
232
232
  catch (err) {
@@ -1 +1 @@
1
- {"version":3,"file":"logUtils.js","sourceRoot":"","sources":["../../../src/utils/logUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAYlC,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,EACL,sBAAsB,EACtB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AAE9D,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAE3F,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EACL,uCAAuC,EACvC,mCAAmC,EACnC,2BAA2B,EAC3B,kCAAkC,EAClC,gCAAgC,EAChC,4BAA4B,EAC5B,oCAAoC,EACpC,gCAAgC,EAChC,kCAAkC,EAClC,8BAA8B,EAC9B,mCAAmC,EACnC,+BAA+B,EAC/B,iBAAiB,GAClB,MAAM,oCAAoC,CAAC;AAE5C;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,GAAsB,EAAE,IAAY;IAChE,MAAM,IAAI,GAAG,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtC,MAAM,UAAU,GAAG,GAAG,CAAC;IACvB,MAAM,kBAAkB,GAAG,IA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AM;YACV,CAAC;YACD,IAAI,OAAO,QAAQ,EAAE,OAAO,KAAK,QAAQ,EAAE,CAAC;gBAC1C,QAAQ,CAAC,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,KAAK,CAAC,wEAAwE,CAAC,CAAC;QACvF,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n AvailabilityData,\n TelemetryItem as Envelope,\n MessageData,\n MonitorDomain,\n PageViewData,\n TelemetryEventData,\n TelemetryExceptionData,\n TelemetryExceptionDetails,\n} from \"../generated/index.js\";\nimport { KnownContextTagKeys, KnownSeverityLevel } from \"../generated/index.js\";\nimport {\n createTagsFromResource,\n hrTimeToDate,\n isSyntheticSource,\n serializeAttribute,\n} from \"./common.js\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from \"@opentelemetry/semantic-conventions\";\nimport { experimentalOpenTelemetryValues } from \"../types.js\";\nimport type { Measurements, Properties, Tags } from \"../types.js\";\nimport { httpSemanticValues, legacySemanticValues, MaxPropertyLengths } from \"../types.js\";\nimport type { Attributes } from \"@opentelemetry/api\";\nimport { diag } from \"@opentelemetry/api\";\nimport {\n ApplicationInsightsAvailabilityBaseType,\n ApplicationInsightsAvailabilityName,\n ApplicationInsightsBaseType,\n ApplicationInsightsCustomEventName,\n ApplicationInsightsEventBaseType,\n ApplicationInsightsEventName,\n ApplicationInsightsExceptionBaseType,\n ApplicationInsightsExceptionName,\n ApplicationInsightsMessageBaseType,\n ApplicationInsightsMessageName,\n ApplicationInsightsPageViewBaseType,\n ApplicationInsightsPageViewName,\n MicrosoftClientIp,\n} from \"./constants/applicationinsights.js\";\n\n/**\n * Log to Azure envelope parsing.\n * @internal\n */\nexport function logToEnvelope(log: ReadableLogRecord, ikey: string): Envelope | undefined {\n const time = hrTimeToDate(log.hrTime);\n const sampleRate = 100;\n const instrumentationKey = ikey;\n const tags = createTagsFromLog(log);\n // eslint-disable-next-line prefer-const\n let [properties, measurements] = createPropertiesFromLog(log);\n let name: string;\n let baseType: string;\n let baseData: MonitorDomain;\n\n const exceptionStacktrace = log.attributes[ATTR_EXCEPTION_STACKTRACE];\n const exceptionType = log.attributes[ATTR_EXCEPTION_TYPE];\n const isExceptionType: boolean = !!(exceptionType && exceptionStacktrace) || false;\n const isMessageType: boolean =\n !log.attributes[ApplicationInsightsBaseType] &&\n !log.attributes[ApplicationInsightsCustomEventName] &&\n !exceptionType;\n if (isExceptionType) {\n const exceptionMessage = log.attributes[ATTR_EXCEPTION_MESSAGE];\n name = ApplicationInsightsExceptionName;\n baseType = ApplicationInsightsExceptionBaseType;\n const exceptionDetails: TelemetryExceptionDetails = {\n typeName: String(exceptionType),\n message: String(exceptionMessage),\n hasFullStack: exceptionStacktrace ? true : false,\n stack: String(exceptionStacktrace),\n };\n const exceptionData: TelemetryExceptionData = {\n exceptions: [exceptionDetails],\n severityLevel: String(getSeverity(log.severityNumber)),\n version: 2,\n };\n baseData = exceptionData;\n } else if (log.attributes[ApplicationInsightsCustomEventName]) {\n name = ApplicationInsightsEventName;\n baseType = ApplicationInsightsEventBaseType;\n const eventData: TelemetryEventData = {\n name: String(log.attributes[ApplicationInsightsCustomEventName]),\n version: 2,\n };\n baseData = eventData;\n measurements = getLegacyApplicationInsightsMeasurements(log);\n } else if (isMessageType) {\n name = ApplicationInsightsMessageName;\n baseType = ApplicationInsightsMessageBaseType;\n const messageData: MessageData = {\n message: String(log.body),\n severityLevel: String(getSeverity(log.severityNumber)),\n version: 2,\n };\n baseData = messageData;\n } else {\n // If Legacy Application Insights Log\n baseType = String(log.attributes[ApplicationInsightsBaseType]);\n name = getLegacyApplicationInsightsName(log);\n baseData = getLegacyApplicationInsightsBaseData(log);\n measurements = getLegacyApplicationInsightsMeasurements(log);\n if (!baseData) {\n // Failed to parse log\n return;\n }\n }\n // Truncate properties\n if (baseData.message) {\n baseData.message = String(baseData.message).substring(0, MaxPropertyLengths.FIFTEEN_BIT);\n }\n if (properties) {\n for (const key of Object.keys(properties)) {\n properties[key] = String(properties[key]).substring(0, MaxPropertyLengths.THIRTEEN_BIT);\n }\n }\n return {\n name,\n sampleRate,\n time,\n instrumentationKey,\n tags,\n version: 1,\n data: {\n baseType,\n baseData: {\n ...baseData,\n properties,\n measurements,\n },\n },\n };\n}\n\nfunction createTagsFromLog(log: ReadableLogRecord): Tags {\n const tags: Tags = createTagsFromResource(log.resource);\n if (log.spanContext?.traceId) {\n tags[KnownContextTagKeys.AiOperationId] = log.spanContext.traceId;\n }\n if (log.spanContext?.spanId) {\n tags[KnownContextTagKeys.AiOperationParentId] = log.spanContext.spanId;\n }\n if (log.attributes[KnownContextTagKeys.AiOperationName]) {\n tags[KnownContextTagKeys.AiOperationName] = log.attributes[\n KnownContextTagKeys.AiOperationName\n ] as string;\n }\n if (isSyntheticSource(log.attributes as Attributes)) {\n tags[KnownContextTagKeys.AiOperationSyntheticSource] = \"True\";\n }\n\n // Set ai.location.ip from microsoft.client.ip if it exists\n const microsoftClientIp = log.attributes?.[MicrosoftClientIp];\n if (microsoftClientIp) {\n tags[KnownContextTagKeys.AiLocationIp] = String(microsoftClientIp);\n }\n\n // Map user ID attributes\n const attributes = log.attributes as Attributes;\n if (attributes[experimentalOpenTelemetryValues.ATTR_ENDUSER_ID]) {\n const endUserId = String(attributes[experimentalOpenTelemetryValues.ATTR_ENDUSER_ID]);\n if (endUserId && endUserId.length > 0) {\n tags[KnownContextTagKeys.AiUserAuthUserId] = endUserId;\n }\n }\n if (attributes[experimentalOpenTelemetryValues.ATTR_ENDUSER_PSEUDO_ID]) {\n const endUserPseudoId = String(\n attributes[experimentalOpenTelemetryValues.ATTR_ENDUSER_PSEUDO_ID],\n );\n if (endUserPseudoId && endUserPseudoId.length > 0) {\n tags[KnownContextTagKeys.AiUserId] = endUserPseudoId;\n }\n }\n\n return tags;\n}\n\nfunction createPropertiesFromLog(log: ReadableLogRecord): [Properties, Measurements] {\n const measurements: Measurements = {};\n const properties: { [propertyName: string]: string } = {};\n if (log.attributes) {\n for (const key of Object.keys(log.attributes)) {\n // Avoid duplication ignoring fields already mapped.\n if (\n !(\n key.startsWith(\"_MS.\") ||\n key.startsWith(\"microsoft\") ||\n legacySemanticValues.includes(key) ||\n httpSemanticValues.includes(key as any) ||\n key === (KnownContextTagKeys.AiOperationName as string)\n )\n ) {\n properties[key] = serializeAttribute(log.attributes[key]);\n }\n }\n }\n return [properties, measurements];\n}\n\n// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#field-severitynumber\nfunction getSeverity(severityNumber: number | undefined): KnownSeverityLevel | undefined {\n if (severityNumber) {\n if (severityNumber > 0 && severityNumber < 9) {\n return KnownSeverityLevel.Verbose;\n } else if (severityNumber >= 9 && severityNumber < 13) {\n return KnownSeverityLevel.Information;\n } else if (severityNumber >= 13 && severityNumber < 17) {\n return KnownSeverityLevel.Warning;\n } else if (severityNumber >= 17 && severityNumber < 21) {\n return KnownSeverityLevel.Error;\n } else if (severityNumber >= 21 && severityNumber < 25) {\n return KnownSeverityLevel.Critical;\n }\n }\n return;\n}\n\nfunction getLegacyApplicationInsightsName(log: ReadableLogRecord): string {\n let name = \"\";\n switch (log.attributes[ApplicationInsightsBaseType]) {\n case ApplicationInsightsAvailabilityBaseType:\n name = ApplicationInsightsAvailabilityName;\n break;\n case ApplicationInsightsExceptionBaseType:\n name = ApplicationInsightsExceptionName;\n break;\n case ApplicationInsightsMessageBaseType:\n name = ApplicationInsightsMessageName;\n break;\n case ApplicationInsightsPageViewBaseType:\n name = ApplicationInsightsPageViewName;\n break;\n case ApplicationInsightsEventBaseType:\n name = ApplicationInsightsEventName;\n break;\n }\n return name;\n}\n\nfunction getLegacyApplicationInsightsMeasurements(log: ReadableLogRecord): Measurements {\n let measurements: Measurements = {};\n if ((log.body as MonitorDomain)?.measurements) {\n measurements = { ...(log.body as MonitorDomain).measurements };\n }\n return measurements;\n}\n\nfunction getLegacyApplicationInsightsBaseData(log: ReadableLogRecord): MonitorDomain {\n let baseData: MonitorDomain = {\n version: 2,\n };\n if (log.body) {\n try {\n switch (log.attributes[ApplicationInsightsBaseType]) {\n case ApplicationInsightsAvailabilityBaseType:\n baseData = log.body as AvailabilityData;\n break;\n case ApplicationInsightsExceptionBaseType:\n baseData = log.body as TelemetryExceptionData;\n break;\n case ApplicationInsightsMessageBaseType:\n baseData = log.body as MessageData;\n break;\n case ApplicationInsightsPageViewBaseType:\n baseData = log.body as PageViewData;\n break;\n case ApplicationInsightsEventBaseType:\n baseData = log.body as TelemetryEventData;\n break;\n }\n if (typeof baseData?.message === \"object\") {\n baseData.message = JSON.stringify(baseData.message);\n }\n } catch (err) {\n diag.error(\"AzureMonitorLogExporter failed to parse Application Insights Telemetry\");\n }\n }\n return baseData;\n}\n"]}
1
+ {"version":3,"file":"logUtils.js","sourceRoot":"","sources":["../../../src/utils/logUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAYlC,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,EACL,sBAAsB,EACtB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AAE9D,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAE3F,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OA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B,CAAC,EAAE,CAAC;gBACpD,KAAK,uCAAuC;oBAC1C,QAAQ,GAAG,GAAG,CAAC,IAAwB,CAAC;oBACxC,MAAM;gBACR,KAAK,oCAAoC;oBACvC,QAAQ,GAAG,GAAG,CAAC,IAA8B,CAAC;oBAC9C,MAAM;gBACR,KAAK,kCAAkC;oBACrC,QAAQ,GAAG,GAAG,CAAC,IAAmB,CAAC;oBACnC,MAAM;gBACR,KAAK,mCAAmC;oBACtC,QAAQ,GAAG,GAAG,CAAC,IAAoB,CAAC;oBACpC,MAAM;gBACR,KAAK,gCAAgC;oBACnC,QAAQ,GAAG,GAAG,CAAC,IAA0B,CAAC;oBAC1C,MAAM;YACV,CAAC;YACD,IAAI,OAAO,QAAQ,EAAE,OAAO,KAAK,QAAQ,EAAE,CAAC;gBAC1C,QAAQ,CAAC,OAAO,GAAG,kBAAkB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;YAC1D,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,CAAC,KAAK,CAAC,wEAAwE,CAAC,CAAC;QACvF,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n AvailabilityData,\n TelemetryItem as Envelope,\n MessageData,\n MonitorDomain,\n PageViewData,\n TelemetryEventData,\n TelemetryExceptionData,\n TelemetryExceptionDetails,\n} from \"../generated/index.js\";\nimport { KnownContextTagKeys, KnownSeverityLevel } from \"../generated/index.js\";\nimport {\n createTagsFromResource,\n hrTimeToDate,\n isSyntheticSource,\n serializeAttribute,\n} from \"./common.js\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from \"@opentelemetry/semantic-conventions\";\nimport { experimentalOpenTelemetryValues } from \"../types.js\";\nimport type { Measurements, Properties, Tags } from \"../types.js\";\nimport { httpSemanticValues, legacySemanticValues, MaxPropertyLengths } from \"../types.js\";\nimport type { Attributes } from \"@opentelemetry/api\";\nimport { diag } from \"@opentelemetry/api\";\nimport {\n ApplicationInsightsAvailabilityBaseType,\n ApplicationInsightsAvailabilityName,\n ApplicationInsightsBaseType,\n ApplicationInsightsCustomEventName,\n ApplicationInsightsEventBaseType,\n ApplicationInsightsEventName,\n ApplicationInsightsExceptionBaseType,\n ApplicationInsightsExceptionName,\n ApplicationInsightsMessageBaseType,\n ApplicationInsightsMessageName,\n ApplicationInsightsPageViewBaseType,\n ApplicationInsightsPageViewName,\n MicrosoftClientIp,\n} from \"./constants/applicationinsights.js\";\n\n/**\n * Log to Azure envelope parsing.\n * @internal\n */\nexport function logToEnvelope(log: ReadableLogRecord, ikey: string): Envelope | undefined {\n const time = hrTimeToDate(log.hrTime);\n const sampleRate = 100;\n const instrumentationKey = ikey;\n const tags = createTagsFromLog(log);\n // eslint-disable-next-line prefer-const\n let [properties, measurements] = createPropertiesFromLog(log);\n let name: string;\n let baseType: string;\n let baseData: MonitorDomain;\n\n const exceptionStacktrace = log.attributes[ATTR_EXCEPTION_STACKTRACE];\n const exceptionType = log.attributes[ATTR_EXCEPTION_TYPE];\n const isExceptionType: boolean = !!(exceptionType && exceptionStacktrace) || false;\n const isMessageType: boolean =\n !log.attributes[ApplicationInsightsBaseType] &&\n !log.attributes[ApplicationInsightsCustomEventName] &&\n !exceptionType;\n if (isExceptionType) {\n const exceptionMessage = log.attributes[ATTR_EXCEPTION_MESSAGE];\n name = ApplicationInsightsExceptionName;\n baseType = ApplicationInsightsExceptionBaseType;\n const exceptionDetails: TelemetryExceptionDetails = {\n typeName: String(exceptionType),\n message: String(exceptionMessage),\n hasFullStack: exceptionStacktrace ? true : false,\n stack: String(exceptionStacktrace),\n };\n const exceptionData: TelemetryExceptionData = {\n exceptions: [exceptionDetails],\n severityLevel: String(getSeverity(log.severityNumber)),\n version: 2,\n };\n baseData = exceptionData;\n } else if (log.attributes[ApplicationInsightsCustomEventName]) {\n name = ApplicationInsightsEventName;\n baseType = ApplicationInsightsEventBaseType;\n const eventData: TelemetryEventData = {\n name: String(log.attributes[ApplicationInsightsCustomEventName]),\n version: 2,\n };\n baseData = eventData;\n measurements = getLegacyApplicationInsightsMeasurements(log);\n } else if (isMessageType) {\n name = ApplicationInsightsMessageName;\n baseType = ApplicationInsightsMessageBaseType;\n const messageData: MessageData = {\n message: serializeAttribute(log.body),\n severityLevel: String(getSeverity(log.severityNumber)),\n version: 2,\n };\n baseData = messageData;\n } else {\n // If Legacy Application Insights Log\n baseType = String(log.attributes[ApplicationInsightsBaseType]);\n name = getLegacyApplicationInsightsName(log);\n baseData = getLegacyApplicationInsightsBaseData(log);\n measurements = getLegacyApplicationInsightsMeasurements(log);\n if (!baseData) {\n // Failed to parse log\n return;\n }\n }\n // Truncate properties\n if (baseData.message) {\n baseData.message = String(baseData.message).substring(0, MaxPropertyLengths.FIFTEEN_BIT);\n }\n if (properties) {\n for (const key of Object.keys(properties)) {\n properties[key] = String(properties[key]).substring(0, MaxPropertyLengths.THIRTEEN_BIT);\n }\n }\n return {\n name,\n sampleRate,\n time,\n instrumentationKey,\n tags,\n version: 1,\n data: {\n baseType,\n baseData: {\n ...baseData,\n properties,\n measurements,\n },\n },\n };\n}\n\nfunction createTagsFromLog(log: ReadableLogRecord): Tags {\n const tags: Tags = createTagsFromResource(log.resource);\n if (log.spanContext?.traceId) {\n tags[KnownContextTagKeys.AiOperationId] = log.spanContext.traceId;\n }\n if (log.spanContext?.spanId) {\n tags[KnownContextTagKeys.AiOperationParentId] = log.spanContext.spanId;\n }\n if (log.attributes[KnownContextTagKeys.AiOperationName]) {\n tags[KnownContextTagKeys.AiOperationName] = log.attributes[\n KnownContextTagKeys.AiOperationName\n ] as string;\n }\n if (isSyntheticSource(log.attributes as Attributes)) {\n tags[KnownContextTagKeys.AiOperationSyntheticSource] = \"True\";\n }\n\n // Set ai.location.ip from microsoft.client.ip if it exists\n const microsoftClientIp = log.attributes?.[MicrosoftClientIp];\n if (microsoftClientIp) {\n tags[KnownContextTagKeys.AiLocationIp] = String(microsoftClientIp);\n }\n\n // Map user ID attributes\n const attributes = log.attributes as Attributes;\n if (attributes[experimentalOpenTelemetryValues.ATTR_ENDUSER_ID]) {\n const endUserId = String(attributes[experimentalOpenTelemetryValues.ATTR_ENDUSER_ID]);\n if (endUserId && endUserId.length > 0) {\n tags[KnownContextTagKeys.AiUserAuthUserId] = endUserId;\n }\n }\n if (attributes[experimentalOpenTelemetryValues.ATTR_ENDUSER_PSEUDO_ID]) {\n const endUserPseudoId = String(\n attributes[experimentalOpenTelemetryValues.ATTR_ENDUSER_PSEUDO_ID],\n );\n if (endUserPseudoId && endUserPseudoId.length > 0) {\n tags[KnownContextTagKeys.AiUserId] = endUserPseudoId;\n }\n }\n\n return tags;\n}\n\nfunction createPropertiesFromLog(log: ReadableLogRecord): [Properties, Measurements] {\n const measurements: Measurements = {};\n const properties: { [propertyName: string]: string } = {};\n if (log.attributes) {\n for (const key of Object.keys(log.attributes)) {\n // Avoid duplication ignoring fields already mapped.\n if (\n !(\n key.startsWith(\"_MS.\") ||\n key.startsWith(\"microsoft\") ||\n legacySemanticValues.includes(key) ||\n httpSemanticValues.includes(key as any) ||\n key === (KnownContextTagKeys.AiOperationName as string)\n )\n ) {\n properties[key] = serializeAttribute(log.attributes[key]);\n }\n }\n }\n return [properties, measurements];\n}\n\n// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#field-severitynumber\nfunction getSeverity(severityNumber: number | undefined): KnownSeverityLevel | undefined {\n if (severityNumber) {\n if (severityNumber > 0 && severityNumber < 9) {\n return KnownSeverityLevel.Verbose;\n } else if (severityNumber >= 9 && severityNumber < 13) {\n return KnownSeverityLevel.Information;\n } else if (severityNumber >= 13 && severityNumber < 17) {\n return KnownSeverityLevel.Warning;\n } else if (severityNumber >= 17 && severityNumber < 21) {\n return KnownSeverityLevel.Error;\n } else if (severityNumber >= 21 && severityNumber < 25) {\n return KnownSeverityLevel.Critical;\n }\n }\n return;\n}\n\nfunction getLegacyApplicationInsightsName(log: ReadableLogRecord): string {\n let name = \"\";\n switch (log.attributes[ApplicationInsightsBaseType]) {\n case ApplicationInsightsAvailabilityBaseType:\n name = ApplicationInsightsAvailabilityName;\n break;\n case ApplicationInsightsExceptionBaseType:\n name = ApplicationInsightsExceptionName;\n break;\n case ApplicationInsightsMessageBaseType:\n name = ApplicationInsightsMessageName;\n break;\n case ApplicationInsightsPageViewBaseType:\n name = ApplicationInsightsPageViewName;\n break;\n case ApplicationInsightsEventBaseType:\n name = ApplicationInsightsEventName;\n break;\n }\n return name;\n}\n\nfunction getLegacyApplicationInsightsMeasurements(log: ReadableLogRecord): Measurements {\n let measurements: Measurements = {};\n if ((log.body as MonitorDomain)?.measurements) {\n measurements = { ...(log.body as MonitorDomain).measurements };\n }\n return measurements;\n}\n\nfunction getLegacyApplicationInsightsBaseData(log: ReadableLogRecord): MonitorDomain {\n let baseData: MonitorDomain = {\n version: 2,\n };\n if (log.body) {\n try {\n switch (log.attributes[ApplicationInsightsBaseType]) {\n case ApplicationInsightsAvailabilityBaseType:\n baseData = log.body as AvailabilityData;\n break;\n case ApplicationInsightsExceptionBaseType:\n baseData = log.body as TelemetryExceptionData;\n break;\n case ApplicationInsightsMessageBaseType:\n baseData = log.body as MessageData;\n break;\n case ApplicationInsightsPageViewBaseType:\n baseData = log.body as PageViewData;\n break;\n case ApplicationInsightsEventBaseType:\n baseData = log.body as TelemetryEventData;\n break;\n }\n if (typeof baseData?.message === \"object\") {\n baseData.message = serializeAttribute(baseData.message);\n }\n } catch (err) {\n diag.error(\"AzureMonitorLogExporter failed to parse Application Insights Telemetry\");\n }\n }\n return baseData;\n}\n"]}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@azure/monitor-opentelemetry-exporter",
3
3
  "author": "Microsoft Corporation",
4
4
  "sdk-type": "client",
5
- "version": "1.0.0-beta.35",
5
+ "version": "1.0.0-beta.36",
6
6
  "description": "Application Insights exporter for the OpenTelemetry JavaScript (Node.js) SDK",
7
7
  "main": "./dist/commonjs/index.js",
8
8
  "module": "./dist/esm/index.js",
@@ -52,17 +52,21 @@
52
52
  "@opentelemetry/instrumentation": "^0.205.0",
53
53
  "@opentelemetry/instrumentation-http": "^0.205.0",
54
54
  "@opentelemetry/sdk-trace-node": "^2.1.0",
55
- "@types/node": "^20.19.0",
56
- "@vitest/browser": "^3.2.3",
57
- "@vitest/coverage-istanbul": "^3.2.3",
58
- "dotenv": "^16.0.0",
59
- "eslint": "^9.33.0",
55
+ "@types/node": "^20.19.24",
56
+ "@vitest/browser-playwright": "^4.0.8",
57
+ "@vitest/coverage-istanbul": "^4.0.8",
58
+ "cross-env": "^7.0.3",
59
+ "dotenv": "^16.6.1",
60
+ "eslint": "^9.39.1",
60
61
  "nock": "^13.5.4",
61
62
  "playwright": "^1.50.1",
62
- "typescript": "~5.8.3",
63
- "vitest": "^3.2.3",
63
+ "prettier": "^3.6.2",
64
+ "rimraf": "^6.1.0",
65
+ "tshy": "^3.0.3",
66
+ "typescript": "~5.9.3",
67
+ "vitest": "^4.0.8",
64
68
  "@azure-tools/test-utils-vitest": "^2.0.1",
65
- "@azure/core-util": "^1.13.1",
69
+ "@azure/core-util": "^1.13.2",
66
70
  "@azure/dev-tool": "^1.0.0",
67
71
  "@azure/eslint-plugin-azure-sdk": "^3.0.0"
68
72
  },
@@ -120,11 +124,11 @@
120
124
  "scripts": {
121
125
  "build": "npm run clean && dev-tool run build-package && dev-tool run extract-api",
122
126
  "build:samples": "tsc -p tsconfig.samples.json",
123
- "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
124
- "clean": "dev-tool run vendored rimraf --glob dist-esm types dist",
127
+ "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
128
+ "clean": "rimraf --glob dist-esm types dist",
125
129
  "execute:samples": "dev-tool samples run samples-dev",
126
130
  "extract-api": "dev-tool run build-package && dev-tool run extract-api",
127
- "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
131
+ "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
128
132
  "generate:client": "autorest --typescript ./swagger/README.md",
129
133
  "lint": "eslint package.json src test",
130
134
  "lint:fix": "eslint package.json src test --fix --fix-type [problem,suggestion]",