@azure/monitor-opentelemetry-exporter 1.0.0-beta.34 → 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.
- package/dist/commonjs/export/statsbeat/customerSDKStats.d.ts +2 -2
- package/dist/commonjs/export/statsbeat/customerSDKStats.d.ts.map +1 -1
- package/dist/commonjs/export/statsbeat/customerSDKStats.js +11 -9
- package/dist/commonjs/export/statsbeat/customerSDKStats.js.map +1 -1
- package/dist/commonjs/export/statsbeat/statsbeatExporter.d.ts +5 -0
- package/dist/commonjs/export/statsbeat/statsbeatExporter.d.ts.map +1 -1
- package/dist/commonjs/export/statsbeat/statsbeatExporter.js +19 -5
- package/dist/commonjs/export/statsbeat/statsbeatExporter.js.map +1 -1
- package/dist/commonjs/generated/applicationInsightsClient.js +1 -1
- package/dist/commonjs/generated/applicationInsightsClient.js.map +1 -1
- package/dist/commonjs/platform/nodejs/baseSender.d.ts.map +1 -1
- package/dist/commonjs/platform/nodejs/baseSender.js +18 -7
- package/dist/commonjs/platform/nodejs/baseSender.js.map +1 -1
- package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.d.ts +15 -0
- package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.d.ts.map +1 -1
- package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.js +65 -2
- package/dist/commonjs/platform/nodejs/persist/fileSystemPersist.js.map +1 -1
- package/dist/commonjs/tsdoc-metadata.json +1 -1
- package/dist/commonjs/utils/constants/applicationinsights.d.ts +1 -1
- package/dist/commonjs/utils/constants/applicationinsights.js +1 -1
- package/dist/commonjs/utils/constants/applicationinsights.js.map +1 -1
- package/dist/commonjs/utils/logUtils.js +2 -2
- package/dist/commonjs/utils/logUtils.js.map +1 -1
- package/dist/esm/export/statsbeat/customerSDKStats.d.ts +2 -2
- package/dist/esm/export/statsbeat/customerSDKStats.d.ts.map +1 -1
- package/dist/esm/export/statsbeat/customerSDKStats.js +11 -9
- package/dist/esm/export/statsbeat/customerSDKStats.js.map +1 -1
- package/dist/esm/export/statsbeat/statsbeatExporter.d.ts +5 -0
- package/dist/esm/export/statsbeat/statsbeatExporter.d.ts.map +1 -1
- package/dist/esm/export/statsbeat/statsbeatExporter.js +19 -5
- package/dist/esm/export/statsbeat/statsbeatExporter.js.map +1 -1
- package/dist/esm/generated/applicationInsightsClient.js +1 -1
- package/dist/esm/generated/applicationInsightsClient.js.map +1 -1
- package/dist/esm/platform/nodejs/baseSender.d.ts.map +1 -1
- package/dist/esm/platform/nodejs/baseSender.js +18 -7
- package/dist/esm/platform/nodejs/baseSender.js.map +1 -1
- package/dist/esm/platform/nodejs/persist/fileSystemPersist.d.ts +15 -0
- package/dist/esm/platform/nodejs/persist/fileSystemPersist.d.ts.map +1 -1
- package/dist/esm/platform/nodejs/persist/fileSystemPersist.js +66 -4
- package/dist/esm/platform/nodejs/persist/fileSystemPersist.js.map +1 -1
- package/dist/esm/utils/constants/applicationinsights.d.ts +1 -1
- package/dist/esm/utils/constants/applicationinsights.js +1 -1
- package/dist/esm/utils/constants/applicationinsights.js.map +1 -1
- package/dist/esm/utils/logUtils.js +2 -2
- package/dist/esm/utils/logUtils.js.map +1 -1
- package/package.json +27 -23
|
@@ -34,4 +34,19 @@ export declare class FileSystemPersist implements PersistentStorage {
|
|
|
34
34
|
private _storeToDisk;
|
|
35
35
|
private _fileCleanupTask;
|
|
36
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Return the deterministic local storage path for a given instrumentation key.
|
|
39
|
+
*
|
|
40
|
+
* On shared Linux hosts the first user to create `/tmp/Microsoft/AzureMonitor` can
|
|
41
|
+
* block others because the directory inherits that user's `umask`. This is avoided by
|
|
42
|
+
* inserting a hash of the instrumentation key, user name, process name, and
|
|
43
|
+
* application directory, giving each user their own subdirectory, e.g.
|
|
44
|
+
* `/tmp/Microsoft-AzureMonitor-1234...../opentelemetry-nodejs-<ikey>`.
|
|
45
|
+
*
|
|
46
|
+
* @param instrumentationKey - Application Insights instrumentation key.
|
|
47
|
+
* @param storageDirectory - Optional custom storage directory path. If not provided, system temp directory is used.
|
|
48
|
+
* @returns Absolute path to the storage directory.
|
|
49
|
+
* @internal
|
|
50
|
+
*/
|
|
51
|
+
export declare function getStorageDirectory(instrumentationKey: string, storageDirectory: string | undefined): string;
|
|
37
52
|
//# sourceMappingURL=fileSystemPersist.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileSystemPersist.d.ts","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"fileSystemPersist.d.ts","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAG3D,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAEtE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAC;AAI7F;;;GAGG;AACH,qBAAa,iBAAkB,YAAW,iBAAiB;IAevD,OAAO,CAAC,QAAQ,CAAC;IACjB,OAAO,CAAC,wBAAwB,CAAC;IAfnC,MAAM,CAAC,cAAc,SAA2B;IAChD,MAAM,CAAC,eAAe,SAAc;IAEpC,oBAAoB,SAA2B;IAC/C,cAAc,SAAkB;IAChC,cAAc,EAAE,MAAM,CAAc;IAEpC,OAAO,CAAC,QAAQ,CAAU;IAC1B,OAAO,CAAC,cAAc,CAAc;IACpC,OAAO,CAAC,iBAAiB,CAA+B;IACxD,OAAO,CAAC,mBAAmB,CAAS;gBAGlC,kBAAkB,EAAE,MAAM,EAClB,QAAQ,CAAC,EAAE,2BAA2B,YAAA,EACtC,wBAAwB,CAAC,EAAE,uBAAuB,YAAA;IAuC5D,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;IAgBlC,KAAK,IAAI,OAAO,CAAC,OAAO,CAAC;IAkB/B;;;OAGG;YACW,mBAAmB;IA8BjC;;;;;OAKG;YACW,YAAY;YAwDZ,gBAAgB;CA+B/B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CACjC,kBAAkB,EAAE,MAAM,EAC1B,gBAAgB,EAAE,MAAM,GAAG,SAAS,GACnC,MAAM,CA+CR"}
|
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
// Licensed under the MIT License.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
5
|
exports.FileSystemPersist = void 0;
|
|
6
|
+
exports.getStorageDirectory = getStorageDirectory;
|
|
6
7
|
const node_os_1 = require("node:os");
|
|
7
8
|
const node_path_1 = require("node:path");
|
|
9
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
10
|
const api_1 = require("@opentelemetry/api");
|
|
9
11
|
const fileAccessControl_js_1 = require("./fileAccessControl.js");
|
|
10
12
|
const fileSystemHelpers_js_1 = require("./fileSystemHelpers.js");
|
|
@@ -17,7 +19,7 @@ const types_js_1 = require("../../../export/statsbeat/types.js");
|
|
|
17
19
|
class FileSystemPersist {
|
|
18
20
|
_options;
|
|
19
21
|
_customerSDKStatsMetrics;
|
|
20
|
-
static TEMPDIR_PREFIX = "
|
|
22
|
+
static TEMPDIR_PREFIX = "opentelemetry-nodejs-";
|
|
21
23
|
static FILENAME_SUFFIX = ".ai.json";
|
|
22
24
|
fileRetemptionPeriod = 2 * 24 * 60 * 60 * 1000; // 2 days
|
|
23
25
|
cleanupTimeOut = 60 * 60 * 1000; // 1 hour
|
|
@@ -45,7 +47,7 @@ class FileSystemPersist {
|
|
|
45
47
|
api_1.diag.error(`No instrumentation key was provided to FileSystemPersister. Files will not be persisted`);
|
|
46
48
|
}
|
|
47
49
|
if (this._enabled) {
|
|
48
|
-
this._tempDirectory = (
|
|
50
|
+
this._tempDirectory = getStorageDirectory(this._instrumentationKey, this._options?.storageDirectory);
|
|
49
51
|
// Starts file cleanup task
|
|
50
52
|
if (!this._fileCleanupTimer) {
|
|
51
53
|
this._fileCleanupTimer = setTimeout(() => {
|
|
@@ -202,4 +204,65 @@ class FileSystemPersist {
|
|
|
202
204
|
}
|
|
203
205
|
}
|
|
204
206
|
exports.FileSystemPersist = FileSystemPersist;
|
|
207
|
+
/**
|
|
208
|
+
* Return the deterministic local storage path for a given instrumentation key.
|
|
209
|
+
*
|
|
210
|
+
* On shared Linux hosts the first user to create `/tmp/Microsoft/AzureMonitor` can
|
|
211
|
+
* block others because the directory inherits that user's `umask`. This is avoided by
|
|
212
|
+
* inserting a hash of the instrumentation key, user name, process name, and
|
|
213
|
+
* application directory, giving each user their own subdirectory, e.g.
|
|
214
|
+
* `/tmp/Microsoft-AzureMonitor-1234...../opentelemetry-nodejs-<ikey>`.
|
|
215
|
+
*
|
|
216
|
+
* @param instrumentationKey - Application Insights instrumentation key.
|
|
217
|
+
* @param storageDirectory - Optional custom storage directory path. If not provided, system temp directory is used.
|
|
218
|
+
* @returns Absolute path to the storage directory.
|
|
219
|
+
* @internal
|
|
220
|
+
*/
|
|
221
|
+
function getStorageDirectory(instrumentationKey, storageDirectory) {
|
|
222
|
+
let userSegment;
|
|
223
|
+
let processName;
|
|
224
|
+
let applicationDirectory;
|
|
225
|
+
try {
|
|
226
|
+
const user = (0, node_os_1.userInfo)();
|
|
227
|
+
userSegment = user.username;
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
userSegment = "";
|
|
231
|
+
}
|
|
232
|
+
if (process.title.length > 0) {
|
|
233
|
+
processName = process.title;
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
processName = "";
|
|
237
|
+
}
|
|
238
|
+
const applicationDir = (0, node_path_1.dirname)(process.cwd() || process.argv[1]);
|
|
239
|
+
if (applicationDir) {
|
|
240
|
+
applicationDirectory = applicationDir;
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
applicationDirectory = "";
|
|
244
|
+
}
|
|
245
|
+
const hash_input = `${instrumentationKey}|${userSegment}|${processName}|${applicationDirectory}`;
|
|
246
|
+
let subDirectory;
|
|
247
|
+
try {
|
|
248
|
+
subDirectory = (0, node_crypto_1.createHash)("sha256").update(hash_input).digest("hex");
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
let hash = 5381;
|
|
252
|
+
for (let i = 0; i < hash_input.length; i++) {
|
|
253
|
+
const char = hash_input.charCodeAt(i);
|
|
254
|
+
hash = (hash << 5) + hash + char;
|
|
255
|
+
hash = hash & hash;
|
|
256
|
+
}
|
|
257
|
+
subDirectory = Math.abs(hash).toString(16);
|
|
258
|
+
}
|
|
259
|
+
let sharedRoot;
|
|
260
|
+
if (storageDirectory) {
|
|
261
|
+
sharedRoot = storageDirectory;
|
|
262
|
+
}
|
|
263
|
+
else {
|
|
264
|
+
sharedRoot = (0, node_os_1.tmpdir)();
|
|
265
|
+
}
|
|
266
|
+
return (0, node_path_1.join)(sharedRoot, "Microsoft-AzureMonitor-" + subDirectory, FileSystemPersist.TEMPDIR_PREFIX + instrumentationKey);
|
|
267
|
+
}
|
|
205
268
|
//# 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,qCAAiC;AACjC,yCAA2C;AAC3C,4CAA0C;AAE1C,iEAA2D;AAC3D,iEAAmF;AAEnF,+CAA8E;AAE9E,iEAA6E;AAG7E;;;GAGG;AACH,MAAa,iBAAiB;IAelB;IACA;IAfV,MAAM,CAAC,cAAc,GAAG,oBAAoB,CAAC;IAC7C,MAAM,CAAC,eAAe,GAAG,UAAU,CAAC;IAEpC,oBAAoB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,SAAS;IACzD,cAA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AAK,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,IAAA,gBAAI,EAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;4BACjD,MAAM,IAAA,iBAAM,EAAC,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,UAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;;AAzNH,8CA0NC","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":"fileSystemPersist.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AA2PlC,kDAkDC;AA3SD,qCAA2C;AAC3C,yC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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,IAAA,gBAAM,GAAE,CAAC;IACxB,CAAC;IACD,OAAO,IAAA,gBAAI,EACT,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.
|
|
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",
|
|
@@ -22,7 +22,7 @@ exports.TIME_SINCE_ENQUEUED = "timeSinceEnqueued";
|
|
|
22
22
|
* AzureMonitorTraceExporter version.
|
|
23
23
|
* @internal
|
|
24
24
|
*/
|
|
25
|
-
exports.packageVersion = "1.0.0-beta.
|
|
25
|
+
exports.packageVersion = "1.0.0-beta.36";
|
|
26
26
|
var DependencyTypes;
|
|
27
27
|
(function (DependencyTypes) {
|
|
28
28
|
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;AACU,QAAA,QAAQ,GAAG,WAAW,CAAC;AACpC;;;GAGG;AACU,QAAA,aAAa,GAAG,cAAc,CAAC;AAC5C;;;GAGG;AACU,QAAA,mBAAmB,GAAG,mBAAmB,CAAC;AACvD;;;GAGG;AACU,QAAA,cAAc,GAAG,eAAe,CAAC;AAE9C,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,+BAAf,eAAe,QAO1B;AAEY,QAAA,sBAAsB,GAAG,uBAAuB,CAAC;AACjD,QAAA,2BAA2B,GAAG,cAAc,CAAC;AAC7C,QAAA,kCAAkC,GAAG,6BAA6B,CAAC;AACnE,QAAA,iBAAiB,GAAG,qBAAqB,CAAC;AAE1C,QAAA,8BAA8B,GAAG,uCAAuC,CAAC;AACzE,QAAA,gCAAgC,GAAG,yCAAyC,CAAC;AAC7E,QAAA,+BAA+B,GAAG,wCAAwC,CAAC;AAC3E,QAAA,mCAAmC,GAAG,4CAA4C,CAAC;AACnF,QAAA,4BAA4B,GAAG,qCAAqC,CAAC;AAErE,QAAA,kCAAkC,GAAG,aAAa,CAAC;AACnD,QAAA,oCAAoC,GAAG,eAAe,CAAC;AACvD,QAAA,mCAAmC,GAAG,cAAc,CAAC;AACrD,QAAA,uCAAuC,GAAG,kBAAkB,CAAC;AAC7D,QAAA,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.
|
|
1
|
+
{"version":3,"file":"applicationinsights.js","sourceRoot":"","sources":["../../../../src/utils/constants/applicationinsights.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC;;;GAGG;AACU,QAAA,QAAQ,GAAG,WAAW,CAAC;AACpC;;;GAGG;AACU,QAAA,aAAa,GAAG,cAAc,CAAC;AAC5C;;;GAGG;AACU,QAAA,mBAAmB,GAAG,mBAAmB,CAAC;AACvD;;;GAGG;AACU,QAAA,cAAc,GAAG,eAAe,CAAC;AAE9C,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,+BAAf,eAAe,QAO1B;AAEY,QAAA,sBAAsB,GAAG,uBAAuB,CAAC;AACjD,QAAA,2BAA2B,GAAG,cAAc,CAAC;AAC7C,QAAA,kCAAkC,GAAG,6BAA6B,CAAC;AACnE,QAAA,iBAAiB,GAAG,qBAAqB,CAAC;AAE1C,QAAA,8BAA8B,GAAG,uCAAuC,CAAC;AACzE,QAAA,gCAAgC,GAAG,yCAAyC,CAAC;AAC7E,QAAA,+BAA+B,GAAG,wCAAwC,CAAC;AAC3E,QAAA,mCAAmC,GAAG,4CAA4C,CAAC;AACnF,QAAA,4BAA4B,GAAG,qCAAqC,CAAC;AAErE,QAAA,kCAAkC,GAAG,aAAa,CAAC;AACnD,QAAA,oCAAoC,GAAG,eAAe,CAAC;AACvD,QAAA,mCAAmC,GAAG,cAAc,CAAC;AACrD,QAAA,uCAAuC,GAAG,kBAAkB,CAAC;AAC7D,QAAA,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"]}
|
|
@@ -61,7 +61,7 @@ function logToEnvelope(log, ikey) {
|
|
|
61
61
|
name = applicationinsights_js_1.ApplicationInsightsMessageName;
|
|
62
62
|
baseType = applicationinsights_js_1.ApplicationInsightsMessageBaseType;
|
|
63
63
|
const messageData = {
|
|
64
|
-
message:
|
|
64
|
+
message: (0, common_js_1.serializeAttribute)(log.body),
|
|
65
65
|
severityLevel: String(getSeverity(log.severityNumber)),
|
|
66
66
|
version: 2,
|
|
67
67
|
};
|
|
@@ -229,7 +229,7 @@ function getLegacyApplicationInsightsBaseData(log) {
|
|
|
229
229
|
break;
|
|
230
230
|
}
|
|
231
231
|
if (typeof baseData?.message === "object") {
|
|
232
|
-
baseData.message =
|
|
232
|
+
baseData.message = (0, common_js_1.serializeAttribute)(baseData.message);
|
|
233
233
|
}
|
|
234
234
|
}
|
|
235
235
|
catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logUtils.js","sourceRoot":"","sources":["../../../src/utils/logUtils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AAkDlC,sCAwFC;AA9HD,oDAAgF;AAChF,2CAKqB;AAErB,8EAI6C;AAC7C,0CAA8D;AAE9D,0CAA2F;AAE3F,4CAA0C;AAC1C,+EAc4C;AAE5C;;;GAGG;AACH,SAAgB,aAAa,CAAC,GAAsB,EAAE,IAAY;IAChE,MAAM,IAAI,GAAG,IAAA,wBAAY,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtC,MAAM,UAAU,GAAG,GAAG,CAAC;IACvB,MAAM,kBAAkB,GAAG,IAAI,CAAC;IAChC,MAAM,IAAI,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAC;IACpC,wCAAwC;IACxC,IAAI,CAAC,UAAU,EAAE,YAAY,CAAC,GAAG,uBAAuB,CAAC,GAAG,CAAC,CAAC;IAC9D,IAAI,IAAY,CAAC;IACjB,IAAI,QAAgB,CAAC;IACrB,IAAI,QAAuB,CAAC;IAE5B,MAAM,mBAAmB,GAAG,GAAG,CAAC,UAAU,CAAC,gDAAyB,CAAC,CAAC;IACtE,MAAM,aAAa,GAAG,GAAG,CAAC,UAAU,CAAC,0CAAmB,CAAC,CAAC;IAC1D,MAAM,eAAe,GAAY,CAAC,CAAC,CAAC,aAAa,IAAI,mBAAmB,CAAC,IAAI,KAAK,CAAC;IACnF,MAAM,aAAa,GACjB,CAAC,GAAG,CAAC,UAAU,CAAC,oDAA2B,CAAC;QAC5C,CAAC,GAAG,CAAC,UAAU,C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AAC,YAAY,EAAE,CAAC;IACjE,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAS,oCAAoC,CAAC,GAAsB;IAClE,IAAI,QAAQ,GAAkB;QAC5B,OAAO,EAAE,CAAC;KACX,CAAC;IACF,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;QACb,IAAI,CAAC;YACH,QAAQ,GAAG,CAAC,UAAU,CAAC,oDAA2B,CAAC,EAAE,CAAC;gBACpD,KAAK,gEAAuC;oBAC1C,QAAQ,GAAG,GAAG,CAAC,IAAwB,CAAC;oBACxC,MAAM;gBACR,KAAK,6DAAoC;oBACvC,QAAQ,GAAG,GAAG,CAAC,IAA8B,CAAC;oBAC9C,MAAM;gBACR,KAAK,2DAAkC;oBACrC,QAAQ,GAAG,GAAG,CAAC,IAAmB,CAAC;oBACnC,MAAM;gBACR,KAAK,4DAAmC;oBACtC,QAAQ,GAAG,GAAG,CAAC,IAAoB,CAAC;oBACpC,MAAM;gBACR,KAAK,yDAAgC;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,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,UAAI,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;;AAkDlC,sCAwFC;AA9HD,oDAAgF;AAChF,2CAKqB;AAErB,8EAI6C;AAC7C,0CAA8D;AAE9D,0CAA2F;AAE3F,4CAA0C;AAC1C,+EAc4C;AAE5C;;;GAGG;AACH,SAAgB,aAAa,CAAC,GAAsB,EAAE,IAAY;IAChE,MAAM,IAAI,GAAG,IAAA,wBAAY,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtC,MAAM,UAAU,GAAG,GAAG,CAAC;IACvB,MAAM,kBAAkB,GAAG,IAAI,CAAC;IAChC,MAAM,IAAI,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAC;IACpC,wCAAwC;IACxC,IAAI,CAAC,UAAU,EAAE,YAAY,CAAC,GAAG,uBAAuB,CAAC,GAAG,CAAC,CAAC;IAC9D,IAAI,IAAY,CAAC;IACjB,IAAI,QAAgB,CAAC;IACrB,IAAI,QAAuB,CAAC;IAE5B,MAAM,mBAAmB,GAAG,GAAG,CAAC,UAAU,CAAC,gDAAyB,CAAC,CAAC;IACtE,MAAM,aAAa,GAAG,GAAG,CAAC,UAAU,CAAC,0CAAmB,CAAC,CAAC;IAC1D,MAAM,eAAe,GAAY,CAAC,CAAC,CAAC,aAAa,IAAI,mBAAmB,CAAC,IAAI,KAAK,CAAC;IACnF,MAAM,aAAa,GACjB,CAAC,GAAG,CAAC,UAAU,CAAC,oDAA2B,CAAC;QAC5C,CAAC,GAAG,CAAC,UAAU,CAAC,2DAAkC,CAAC;QACnD,CAAC,aAAa,CAAC;IACjB,IAAI,eAAe,EAAE,CAAC;QACpB,MAAM,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AS,oCAAoC,CAAC,GAAsB;IAClE,IAAI,QAAQ,GAAkB;QAC5B,OAAO,EAAE,CAAC;KACX,CAAC;IACF,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;QACb,IAAI,CAAC;YACH,QAAQ,GAAG,CAAC,UAAU,CAAC,oDAA2B,CAAC,EAAE,CAAC;gBACpD,KAAK,gEAAuC;oBAC1C,QAAQ,GAAG,GAAG,CAAC,IAAwB,CAAC;oBACxC,MAAM;gBACR,KAAK,6DAAoC;oBACvC,QAAQ,GAAG,GAAG,CAAC,IAA8B,CAAC;oBAC9C,MAAM;gBACR,KAAK,2DAAkC;oBACrC,QAAQ,GAAG,GAAG,CAAC,IAAmB,CAAC;oBACnC,MAAM;gBACR,KAAK,4DAAmC;oBACtC,QAAQ,GAAG,GAAG,CAAC,IAAoB,CAAC;oBACpC,MAAM;gBACR,KAAK,yDAAgC;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,IAAA,8BAAkB,EAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;YAC1D,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,UAAI,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"]}
|
|
@@ -30,9 +30,9 @@ export declare class CustomerSDKStatsMetrics extends StatsbeatMetrics {
|
|
|
30
30
|
/**
|
|
31
31
|
* Get singleton instance of CustomerSDKStatsMetrics
|
|
32
32
|
* @param options - Configuration options for customer SDK Stats metrics
|
|
33
|
-
* @returns
|
|
33
|
+
* @returns Promise of the singleton instance
|
|
34
34
|
*/
|
|
35
|
-
static getInstance(options: StatsbeatOptions): CustomerSDKStatsMetrics
|
|
35
|
+
static getInstance(options: StatsbeatOptions): Promise<CustomerSDKStatsMetrics>;
|
|
36
36
|
/**
|
|
37
37
|
* Shutdown the singleton instance
|
|
38
38
|
* Used for cleanup and complete shutdown
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customerSDKStats.d.ts","sourceRoot":"","sources":["../../../../src/export/statsbeat/customerSDKStats.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"customerSDKStats.d.ts","sourceRoot":"","sources":["../../../../src/export/statsbeat/customerSDKStats.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,KAAK,EAA8B,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,EAEL,QAAQ,EACR,SAAS,EACT,aAAa,EAGd,MAAM,YAAY,CAAC;AACpB,OAAO,EAA6C,aAAa,EAAE,MAAM,YAAY,CAAC;AAItF,OAAO,KAAK,EAAE,aAAa,IAAI,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAE1E;;;;;;GAMG;AACH,qBAAa,uBAAwB,SAAQ,gBAAgB;IAC3D,OAAO,CAAC,MAAM,CAAC,SAAS,CAAsC;IAE9D,OAAO,CAAC,uBAAuB,CAAkB;IACjD,OAAO,CAAC,qBAAqB,CAAQ;IACrC,OAAO,CAAC,6BAA6B,CAAgB;IACrD,OAAO,CAAC,w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,GAC5B,IAAI;IA6BP;;;;;;OAMG;IACH,OAAO,CAAC,cAAc;IAgCtB;;;;OAIG;IACH,OAAO,CAAC,0BAA0B;IAMlC;;;;OAIG;IACI,4BAA4B,CAAC,QAAQ,EAAE,QAAQ,GAAG,aAAa;IAqCtE;;;;OAIG;IACI,+BAA+B,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,GAAG,SAAS;IAiB/E;;;;OAIG;IACI,cAAc,CAAC,KAAK,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO;CAsB3E"}
|
|
@@ -7,7 +7,6 @@ import { StatsbeatMetrics } from "./statsbeatMetrics.js";
|
|
|
7
7
|
import { CustomerSDKStats, DropCode, RetryCode, ExceptionType, DropReason, RetryReason, } from "./types.js";
|
|
8
8
|
import { CustomSDKStatsCounter, STATSBEAT_LANGUAGE, TelemetryType } from "./types.js";
|
|
9
9
|
import { getAttachType } from "../../utils/metricUtils.js";
|
|
10
|
-
import { AzureMonitorStatsbeatExporter } from "./statsbeatExporter.js";
|
|
11
10
|
import { BreezePerformanceCounterNames } from "../../types.js";
|
|
12
11
|
/**
|
|
13
12
|
* Class that handles customer-facing SDK Stats metrics
|
|
@@ -35,12 +34,9 @@ export class CustomerSDKStatsMetrics extends StatsbeatMetrics {
|
|
|
35
34
|
itemRetryCountGauge;
|
|
36
35
|
// Customer SDK Stats properties
|
|
37
36
|
customerProperties;
|
|
38
|
-
constructor(options) {
|
|
37
|
+
constructor(options, exporter) {
|
|
39
38
|
super();
|
|
40
|
-
|
|
41
|
-
connectionString: `InstrumentationKey=${options.instrumentationKey};IngestionEndpoint=${options.endpointUrl}`,
|
|
42
|
-
};
|
|
43
|
-
this.customerSDKStatsExporter = new AzureMonitorStatsbeatExporter(exporterConfig);
|
|
39
|
+
this.customerSDKStatsExporter = exporter;
|
|
44
40
|
// Exports Customer SDK Stats every 15 minutes
|
|
45
41
|
const customerMetricReaderOptions = {
|
|
46
42
|
exporter: this.customerSDKStatsExporter,
|
|
@@ -71,11 +67,17 @@ export class CustomerSDKStatsMetrics extends StatsbeatMetrics {
|
|
|
71
67
|
/**
|
|
72
68
|
* Get singleton instance of CustomerSDKStatsMetrics
|
|
73
69
|
* @param options - Configuration options for customer SDK Stats metrics
|
|
74
|
-
* @returns
|
|
70
|
+
* @returns Promise of the singleton instance
|
|
75
71
|
*/
|
|
76
|
-
static getInstance(options) {
|
|
72
|
+
static async getInstance(options) {
|
|
77
73
|
if (!CustomerSDKStatsMetrics._instance) {
|
|
78
|
-
|
|
74
|
+
// Use dynamic import to break circular dependency
|
|
75
|
+
const { AzureMonitorStatsbeatExporter } = await import("./statsbeatExporter.js");
|
|
76
|
+
const customerStatsExporterConfig = {
|
|
77
|
+
connectionString: `InstrumentationKey=${options.instrumentationKey};IngestionEndpoint=${options.endpointUrl}`,
|
|
78
|
+
};
|
|
79
|
+
const exporter = new AzureMonitorStatsbeatExporter(customerStatsExporterConfig);
|
|
80
|
+
CustomerSDKStatsMetrics._instance = new CustomerSDKStatsMetrics(options, exporter);
|
|
79
81
|
}
|
|
80
82
|
return CustomerSDKStatsMetrics._instance;
|
|
81
83
|
}
|