first commit

This commit is contained in:
Stefan Hacker
2026-04-03 09:38:48 +02:00
commit 37ad745546
47450 changed files with 3120798 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
export interface AgentLogger {
log(message?: any, ...optional: any[]): void;
error(message?: any, ...optional: any[]): void;
}
export declare const enum SeverityLevel {
ERROR = "ERROR",
WARN = "WARN",
INFO = "INFO",
}
export interface DiagnosticLog {
/**
* UTC
*/
time: string;
/**
* Log severity, INFO, WARN, ERROR
*/
level: SeverityLevel;
/**
* The logger writing this message. Usually the fully-qualified class or package name
*/
logger: string;
/**
* The log message
*/
message: string;
/**
* Exception (as string)
*/
exception?: string;
/**
* Any custom data related to the error/application/operation. Each field should have a string value
* Examples: operation, siteName, ikey, extensionVersion, sdkVersion, subscriptionId
*/
properties: {
[key: string]: string;
};
}
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
;
//# sourceMappingURL=DataModel.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"DataModel.js","sourceRoot":"","sources":["../../Bootstrap/DataModel.ts"],"names":[],"mappings":";;AASC,CAAC","sourcesContent":["export interface AgentLogger {\r\n log(message?: any, ...optional: any[]): void;\r\n error(message?: any, ...optional: any[]): void;\r\n}\r\n\r\nexport const enum SeverityLevel {\r\n ERROR = \"ERROR\",\r\n WARN = \"WARN\",\r\n INFO = \"INFO\"\r\n};\r\n\r\nexport interface DiagnosticLog {\r\n /**\r\n * UTC\r\n */\r\n time: string;\r\n\r\n /**\r\n * Log severity, INFO, WARN, ERROR\r\n */\r\n level: SeverityLevel;\r\n\r\n /**\r\n * The logger writing this message. Usually the fully-qualified class or package name\r\n */\r\n logger: string;\r\n\r\n /**\r\n * The log message\r\n */\r\n message: string;\r\n\r\n /**\r\n * Exception (as string)\r\n */\r\n exception?: string\r\n\r\n /**\r\n * Any custom data related to the error/application/operation. Each field should have a string value\r\n * Examples: operation, siteName, ikey, extensionVersion, sdkVersion, subscriptionId\r\n */\r\n properties: { [key: string]: string };\r\n}\r\n"]}
+19
View File
@@ -0,0 +1,19 @@
import * as types from "../applicationinsights";
import { StatusLogger } from "./StatusLogger";
import { DiagnosticLogger } from "./DiagnosticLogger";
/**
* Sets the attach-time logger
* @param logger logger which implements the `AgentLogger` interface
*/
export declare function setLogger(logger: DiagnosticLogger): DiagnosticLogger;
/**
* Sets the string which is prefixed to the existing sdkVersion, e.g. `ad_`, `alr_`
* @param prefix string prefix, including underscore. Defaults to `ad_`
*/
export declare function setUsagePrefix(prefix: string): void;
export declare function setStatusLogger(statusLogger: StatusLogger): void;
/**
* Try to setup and start this app insights instance if attach is enabled.
* @param setupString connection string or instrumentation key
*/
export declare function setupAndStart(setupString?: any): typeof types | null;
+105
View File
@@ -0,0 +1,105 @@
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var Helpers = require("./Helpers");
var Constants = require("../Declarations/Constants");
var StatusLogger_1 = require("./StatusLogger");
var DiagnosticLogger_1 = require("./DiagnosticLogger");
// Private configuration vars
var _appInsights;
var _prefix = "ad_"; // App Services, Default
var _logger = new DiagnosticLogger_1.DiagnosticLogger(console);
var _statusLogger = new StatusLogger_1.StatusLogger(console);
// Env var local constants
var _setupString = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || process.env.APPINSIGHTS_INSTRUMENTATIONKEY;
var forceStart = process.env.APPLICATIONINSIGHTS_FORCE_START === "true";
// Other local constants
var defaultStatus = __assign({}, StatusLogger_1.StatusLogger.DEFAULT_STATUS, { Ikey: _setupString });
/**
* Sets the attach-time logger
* @param logger logger which implements the `AgentLogger` interface
*/
function setLogger(logger) {
return _logger = logger;
}
exports.setLogger = setLogger;
/**
* Sets the string which is prefixed to the existing sdkVersion, e.g. `ad_`, `alr_`
* @param prefix string prefix, including underscore. Defaults to `ad_`
*/
function setUsagePrefix(prefix) {
_prefix = prefix;
}
exports.setUsagePrefix = setUsagePrefix;
function setStatusLogger(statusLogger) {
_statusLogger = statusLogger;
}
exports.setStatusLogger = setStatusLogger;
/**
* Try to setup and start this app insights instance if attach is enabled.
* @param setupString connection string or instrumentation key
*/
function setupAndStart(setupString) {
if (setupString === void 0) { setupString = _setupString; }
// If app already contains SDK, skip agent attach
if (!forceStart && Helpers.sdkAlreadyExists(_logger)) {
_statusLogger.logStatus(__assign({}, defaultStatus, { AgentInitializedSuccessfully: false, SDKPresent: true, Reason: "SDK already exists" }));
return null;
}
if (!setupString) {
var message = "Application Insights wanted to be started, but no Connection String or Instrumentation Key was provided";
_logger.logError(message, setupString);
_statusLogger.logStatus(__assign({}, defaultStatus, { AgentInitializedSuccessfully: false, Reason: message }));
return null;
}
try {
_appInsights = require("../applicationinsights");
if (_appInsights.defaultClient) {
// setupAndStart was already called, return the result
_logger.logError("Setup was attempted on the Application Insights Client multiple times. Aborting and returning the first client instance");
return _appInsights;
}
var prefixInternalSdkVersion = function (envelope, _contextObjects) {
try {
var appInsightsSDKVersion = _appInsights.defaultClient.context.keys.internalSdkVersion;
envelope.tags[appInsightsSDKVersion] = _prefix + envelope.tags[appInsightsSDKVersion];
}
catch (e) {
_logger.logError("Error prefixing SDK version", e);
}
return true;
};
var copyOverPrefixInternalSdkVersionToHeartBeatMetric = function (envelope, _contextObjects) {
var appInsightsSDKVersion = _appInsights.defaultClient.context.keys.internalSdkVersion;
var sdkVersion = envelope.tags[appInsightsSDKVersion] || "";
if (envelope.name === Constants.HeartBeatMetricName) {
(envelope.data.baseData).properties = (envelope.data.baseData).properties || {};
(envelope.data.baseData).properties["sdk"] = sdkVersion;
}
return true;
};
// Instrument the SDK
_appInsights.setup(setupString).setSendLiveMetrics(true);
_appInsights.defaultClient.setAutoPopulateAzureProperties(true);
_appInsights.defaultClient.addTelemetryProcessor(prefixInternalSdkVersion);
_appInsights.defaultClient.addTelemetryProcessor(copyOverPrefixInternalSdkVersionToHeartBeatMetric);
_appInsights.start();
// Agent successfully instrumented the SDK
_logger.logMessage("Application Insights was started with setupString: " + setupString);
_statusLogger.logStatus(__assign({}, defaultStatus, { AgentInitializedSuccessfully: true }));
}
catch (e) {
_logger.logError("Error setting up Application Insights", e);
_statusLogger.logStatus(__assign({}, defaultStatus, { AgentInitializedSuccessfully: false, Reason: "Error setting up Application Insights: " + (e && e.message) }));
}
return _appInsights;
}
exports.setupAndStart = setupAndStart;
//# sourceMappingURL=Default.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
import * as DataModel from "./DataModel";
export declare class DiagnosticLogger {
private _writer;
static readonly DEFAULT_FILE_NAME: string;
static readonly DEFAULT_LOG_DIR: string;
static DefaultEnvelope: DataModel.DiagnosticLog;
constructor(_writer?: DataModel.AgentLogger);
logMessage(message: DataModel.DiagnosticLog | string, cb?: (err: Error) => void): void;
logError(message: DataModel.DiagnosticLog | string, cb?: (err: Error) => void): void;
}
+69
View File
@@ -0,0 +1,69 @@
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var path = require("path");
var DataModel = require("./DataModel");
var FileWriter_1 = require("./FileWriter");
var FileHelpers_1 = require("./Helpers/FileHelpers");
var DiagnosticLogger = (function () {
function DiagnosticLogger(_writer) {
if (_writer === void 0) { _writer = console; }
this._writer = _writer;
}
DiagnosticLogger.prototype.logMessage = function (message, cb) {
if (typeof cb === "function" && this._writer instanceof FileWriter_1.FileWriter) {
this._writer.callback = cb;
}
if (typeof message === "string") {
var diagnosticMessage = __assign({}, DiagnosticLogger.DefaultEnvelope, { message: message, level: "INFO" /* INFO */, time: new Date().toISOString() });
this._writer.log(diagnosticMessage);
}
else {
if (message.level === "ERROR" /* ERROR */) {
this._writer.error(message);
}
else {
this._writer.log(message);
}
}
};
DiagnosticLogger.prototype.logError = function (message, cb) {
if (typeof cb === "function" && this._writer instanceof FileWriter_1.FileWriter) {
this._writer.callback = cb;
}
if (typeof message === "string") {
var diagnosticMessage = __assign({}, DiagnosticLogger.DefaultEnvelope, { message: message, level: "ERROR" /* ERROR */, time: new Date().toUTCString() });
this._writer.error(diagnosticMessage);
}
else {
this._writer.error(message);
}
};
DiagnosticLogger.DEFAULT_FILE_NAME = "application-insights-extension.log";
DiagnosticLogger.DEFAULT_LOG_DIR = process.env.APPLICATIONINSIGHTS_LOGDIR || path.join(FileHelpers_1.homedir, "LogFiles/ApplicationInsights");
DiagnosticLogger.DefaultEnvelope = {
message: null,
level: null,
time: null,
logger: "applicationinsights.extension.diagnostics",
properties: {
language: "nodejs",
operation: "Startup",
siteName: process.env.WEBSITE_SITE_NAME,
ikey: process.env.APPINSIGHTS_INSTRUMENTATIONKEY,
extensionVersion: process.env.ApplicationInsightsAgent_EXTENSION_VERSION,
sdkVersion: "1.8.10",
subscriptionId: process.env.WEBSITE_OWNER_NAME ? process.env.WEBSITE_OWNER_NAME.split("+")[0] : null,
}
};
return DiagnosticLogger;
}());
exports.DiagnosticLogger = DiagnosticLogger;
//# sourceMappingURL=DiagnosticLogger.js.map
@@ -0,0 +1 @@
{"version":3,"file":"DiagnosticLogger.js","sourceRoot":"","sources":["../../Bootstrap/DiagnosticLogger.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;;;;;;;AAEb,2BAA6B;AAE7B,uCAAyC;AACzC,2CAA0C;AAC1C,qDAAgD;AAEhD;IAmBI,0BAAoB,OAAwC;QAAxC,wBAAA,EAAA,iBAAwC;QAAxC,YAAO,GAAP,OAAO,CAAiC;IAAG,CAAC;IAEhE,qCAAU,GAAV,UAAW,OAAyC,EAAE,EAAyB;QAC3E,EAAE,CAAC,CAAC,OAAO,EAAE,KAAK,UAAU,IAAI,IAAI,CAAC,OAAO,YAAY,uBAAU,CAAC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,CAAC;QAChC,CAAC;IACL,CAAC;IAxDsB,kCAAiB,GAAW,oCAAoC,CAAC;IACjE,gCAAe,GAAW,OAAO,CAAC,GAAG,CAAC,0BAA0B,IAAI,IAAI,CAAC,IAAI,CAAC,qBAAO,EAAE,8BAA8B,CAAC,CAAC;IAChI,gCAAe,GAA4B;QACrD,OAAO,EAAE,IAAI;QACb,KAAK,EAAE,IAAI;QACX,IAAI,EAAE,IAAI;QACV,MAAM,EAAE,2CAA2C;QACnD,UAAU,EAAE;YACR,QAAQ,EAAE,QAAQ;YAClB,SAAS,EAAE,SAAS;YACpB,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,iBAAiB;YACvC,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,8BAA8B;YAChD,gBAAgB,EAAE,OAAO,CAAC,GAAG,CAAC,0CAA0C;YACxE,UAAU,EAAE,QAAQ;YACpB,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,kBAAkB,GAAG,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;SACvG;KACJ,CAAA;IAyCL,uBAAC;CAAA,AA1DD,IA0DC;AA1DY,4CAAgB","sourcesContent":["\"use strict\";\r\n\r\nimport * as path from \"path\";\r\nimport * as fs from \"fs\";\r\nimport * as DataModel from \"./DataModel\";\r\nimport { FileWriter } from \"./FileWriter\";\r\nimport { homedir } from \"./Helpers/FileHelpers\";\r\n\r\nexport class DiagnosticLogger {\r\n public static readonly DEFAULT_FILE_NAME: string = \"application-insights-extension.log\";\r\n public static readonly DEFAULT_LOG_DIR: string = process.env.APPLICATIONINSIGHTS_LOGDIR || path.join(homedir, \"LogFiles/ApplicationInsights\");\r\n public static DefaultEnvelope: DataModel.DiagnosticLog = {\r\n message: null,\r\n level: null,\r\n time: null,\r\n logger: \"applicationinsights.extension.diagnostics\",\r\n properties: {\r\n language: \"nodejs\",\r\n operation: \"Startup\",\r\n siteName: process.env.WEBSITE_SITE_NAME,\r\n ikey: process.env.APPINSIGHTS_INSTRUMENTATIONKEY,\r\n extensionVersion: process.env.ApplicationInsightsAgent_EXTENSION_VERSION,\r\n sdkVersion: \"1.8.10\",\r\n subscriptionId: process.env.WEBSITE_OWNER_NAME ? process.env.WEBSITE_OWNER_NAME.split(\"+\")[0] : null,\r\n }\r\n }\r\n\r\n constructor(private _writer: DataModel.AgentLogger = console) {}\r\n\r\n logMessage(message: DataModel.DiagnosticLog | string, cb?: (err: Error) => void) {\r\n if (typeof cb === \"function\" && this._writer instanceof FileWriter) {\r\n this._writer.callback = cb;\r\n }\r\n if (typeof message === \"string\") {\r\n const diagnosticMessage: DataModel.DiagnosticLog = {\r\n ...DiagnosticLogger.DefaultEnvelope,\r\n message,\r\n level: DataModel.SeverityLevel.INFO,\r\n time: new Date().toISOString(),\r\n };\r\n this._writer.log(diagnosticMessage);\r\n } else {\r\n if (message.level === DataModel.SeverityLevel.ERROR) {\r\n this._writer.error(message);\r\n } else {\r\n this._writer.log(message);\r\n }\r\n }\r\n }\r\n\r\n logError(message: DataModel.DiagnosticLog | string, cb?: (err: Error) => void) {\r\n if (typeof cb === \"function\" && this._writer instanceof FileWriter) {\r\n this._writer.callback = cb;\r\n }\r\n if (typeof message === \"string\") {\r\n const diagnosticMessage: DataModel.DiagnosticLog = {\r\n ...DiagnosticLogger.DefaultEnvelope,\r\n message,\r\n level: DataModel.SeverityLevel.ERROR,\r\n time: new Date().toUTCString()\r\n };\r\n this._writer.error(diagnosticMessage);\r\n } else {\r\n this._writer.error(message);\r\n }\r\n }\r\n}\r\n"]}
+27
View File
@@ -0,0 +1,27 @@
import * as DataModel from "./DataModel";
export interface FileWriterOptions {
append: boolean;
deleteOnExit: boolean;
sizeLimit: number;
renamePolicy: "rolling" | "overwrite" | "stop";
chmod: number;
}
export declare const homedir: any;
export declare class FileWriter implements DataModel.AgentLogger {
private _filepath;
private _filename;
callback: (_err: Error) => void;
private _ready;
private _options;
private static _fullpathsToDelete;
private static _listenerAttached;
private static DEFAULT_OPTIONS;
static isNodeVersionCompatible(): boolean;
constructor(_filepath: string, _filename: string, options?: Partial<FileWriterOptions>);
log(message: any): void;
error(message: any): void;
private _appendFile(message);
private _writeFile(message);
private static _addCloseHandler();
private _shouldRenameFile(callback?);
}
+136
View File
@@ -0,0 +1,136 @@
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var path = require("path");
var fs = require("fs");
var FileHelpers = require("./Helpers/FileHelpers");
exports.homedir = FileHelpers.homedir;
var FileWriter = (function () {
// leave at "keep at single file only", "write up to certain size limit", "clear old file on process startup"
function FileWriter(_filepath, _filename, options) {
this._filepath = _filepath;
this._filename = _filename;
this.callback = function (_err) { }; // no-op
this._ready = false;
this._options = __assign({}, FileWriter.DEFAULT_OPTIONS, options);
this._ready = FileWriter.isNodeVersionCompatible() && FileHelpers.makeStatusDirs(this._filepath);
if (this._options.deleteOnExit) {
FileWriter._addCloseHandler();
FileWriter._fullpathsToDelete.push(path.join(this._filepath, this._filename));
}
}
FileWriter.isNodeVersionCompatible = function () {
var majVer = process.versions.node.split(".")[0];
return parseInt(majVer) >= 1;
};
FileWriter.prototype.log = function (message) {
var _this = this;
if (this._ready) {
var data_1 = typeof message === "object"
? JSON.stringify(message)
: message.toString();
// Check if existing file needs to be renamed
this._shouldRenameFile(function (err, shouldRename) {
if (err)
return;
if (shouldRename) {
if (_this._options.renamePolicy === "rolling") {
FileHelpers.renameCurrentFile(_this._filepath, _this._filename, function (renameErr, renamedFullpath) {
if (renameErr)
return;
FileWriter._fullpathsToDelete.push(renamedFullpath);
_this._options.append
? _this._appendFile(data_1 + "\n")
: _this._writeFile(data_1);
});
}
else if (_this._options.renamePolicy === "overwrite") {
// Clear the current file
_this._writeFile(data_1);
}
else if (_this._options.renamePolicy === "stop") {
// Stop future logging
_this._ready = false;
}
}
else {
_this._options.append
? _this._appendFile(data_1 + "\n")
: _this._writeFile(data_1);
}
});
}
};
FileWriter.prototype.error = function (message) {
this.log(message);
};
FileWriter.prototype._appendFile = function (message) {
var _this = this;
var fullpath = path.join(this._filepath, this._filename);
fs.appendFile(fullpath, message, function (err) {
_this.callback(err);
});
};
FileWriter.prototype._writeFile = function (message) {
var fullpath = path.join(this._filepath, this._filename);
fs.writeFile(fullpath, message, { mode: this._options.chmod }, this.callback);
};
FileWriter._addCloseHandler = function () {
if (!FileWriter._listenerAttached) {
process.on("exit", function () {
FileWriter._fullpathsToDelete.forEach(function (filename) {
try {
fs.unlinkSync(filename);
}
catch (err) { }
});
});
FileWriter._listenerAttached = true;
}
};
FileWriter.prototype._shouldRenameFile = function (callback) {
var _this = this;
var fullpath = path.join(this._filepath, this._filename);
fs.stat(fullpath, function (err, stats) {
if (err) {
if (err.code === "ENOENT" && typeof callback === "function") {
callback(null, false);
}
else if (typeof callback === "function") {
callback(err);
}
return;
}
if (stats.size > _this._options.sizeLimit) {
callback(null, true);
}
else {
var createDate = new Date(stats.birthtime);
var currentDate = new Date();
var result = (createDate.getUTCDate() !== currentDate.getUTCDate() ||
createDate.getUTCMonth() !== currentDate.getUTCMonth() ||
createDate.getUTCFullYear() !== currentDate.getUTCFullYear());
callback(null, result);
}
});
};
FileWriter._fullpathsToDelete = [];
FileWriter._listenerAttached = false;
FileWriter.DEFAULT_OPTIONS = {
append: false,
deleteOnExit: true,
sizeLimit: 10 * 1024,
renamePolicy: "stop",
chmod: 420 // rw/r/r
};
return FileWriter;
}());
exports.FileWriter = FileWriter;
//# sourceMappingURL=FileWriter.js.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
import { DiagnosticLogger } from "./DiagnosticLogger";
export declare function sdkAlreadyExists(_logger: DiagnosticLogger): boolean;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function sdkAlreadyExists(_logger) {
try {
// appInstance should either resolve to user SDK or crash. If it resolves to attach SDK, user probably modified their NODE_PATH
var appInstance = void 0;
try {
// Node 8.9+
appInstance = require.resolve("applicationinsights", { paths: [process.cwd()] });
}
catch (e) {
// Node <8.9
appInstance = require.resolve(process.cwd() + "/node_modules/applicationinsights");
}
// If loaded instance is in Azure machine home path do not attach the SDK, this means customer already instrumented their app
if (appInstance.indexOf("home") > -1) {
_logger.logMessage("applicationinsights module is already installed in this application; not re-attaching. Installed SDK location: " +
appInstance);
return true;
}
else {
// ApplicationInsights could be loaded outside of customer application, attach in this case
return false;
}
}
catch (e) {
// crashed while trying to resolve "applicationinsights", so SDK does not exist. Attach appinsights
return false;
}
}
exports.sdkAlreadyExists = sdkAlreadyExists;
//# sourceMappingURL=Helpers.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Helpers.js","sourceRoot":"","sources":["../../Bootstrap/Helpers.ts"],"names":[],"mappings":";;AAEA,0BAAiC,OAAyB;IACtD,IAAI,CAAC;QACD,+HAA+H;QAC/H,IAAI,WAAW,SAAQ,CAAC;QACxB,IAAI,CAAC;YACD,YAAY;YACZ,WAAW,GAAI,OAAO,CAAC,OAAe,CAAC,qBAAqB,EAAE,EAAE,KAAK,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;QAC9F,CAAC;QAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACT,YAAY;YACZ,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,mCAAmC,CAAC,CAAC;QACvF,CAAC;QACD,6HAA6H;QAC7H,EAAE,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YACnC,OAAO,CAAC,UAAU,CACd,iHAAiH;gBACjH,WAAW,CACd,CAAC;YACF,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QACD,IAAI,CAAC,CAAC;YACF,2FAA2F;YAC3F,MAAM,CAAC,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;IAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACT,mGAAmG;QACnG,MAAM,CAAC,KAAK,CAAC;IACjB,CAAC;AACL,CAAC;AA3BD,4CA2BC","sourcesContent":["import { DiagnosticLogger } from \"./DiagnosticLogger\";\r\n\r\nexport function sdkAlreadyExists(_logger: DiagnosticLogger): boolean {\r\n try {\r\n // appInstance should either resolve to user SDK or crash. If it resolves to attach SDK, user probably modified their NODE_PATH\r\n let appInstance: string;\r\n try {\r\n // Node 8.9+\r\n appInstance = (require.resolve as any)(\"applicationinsights\", { paths: [process.cwd()] });\r\n } catch (e) {\r\n // Node <8.9\r\n appInstance = require.resolve(process.cwd() + \"/node_modules/applicationinsights\");\r\n }\r\n // If loaded instance is in Azure machine home path do not attach the SDK, this means customer already instrumented their app\r\n if (appInstance.indexOf(\"home\") > -1) {\r\n _logger.logMessage(\r\n \"applicationinsights module is already installed in this application; not re-attaching. Installed SDK location: \" +\r\n appInstance\r\n );\r\n return true;\r\n }\r\n else {\r\n // ApplicationInsights could be loaded outside of customer application, attach in this case\r\n return false;\r\n }\r\n } catch (e) {\r\n // crashed while trying to resolve \"applicationinsights\", so SDK does not exist. Attach appinsights\r\n return false;\r\n }\r\n}\r\n"]}
@@ -0,0 +1,3 @@
export declare const homedir: any;
export declare function makeStatusDirs(filepath: string): boolean;
export declare function renameCurrentFile(filepath: string, filename: string, callback?: (err: Error | null, destfullpath?: string) => void): void;
+70
View File
@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var path = require("path");
var fs = require("fs");
var os = require("os");
exports.homedir = os.homedir ? os.homedir() : (process.env[(process.platform == "win32") ? "USERPROFILE" : "HOME"]);
/**
* Zero dependencies: recursive mkdir
*/
function mkDirByPathSync(HOME_DIR, targetDir, _a) {
var _b = (_a === void 0 ? {} : _a).isRelativeToScript, isRelativeToScript = _b === void 0 ? false : _b;
var sep = path.sep;
var initDir = path.isAbsolute(targetDir) ? sep : "";
var baseDir = isRelativeToScript ? __dirname : ".";
return targetDir.split(sep).reduce(function (parentDir, childDir) {
var curDir = path.resolve(baseDir, parentDir, childDir);
try {
// Don't try to recreate homedir
if (HOME_DIR.indexOf(curDir) === -1) {
fs.mkdirSync(curDir);
}
}
catch (err) {
if (err.code === "EEXIST") {
return curDir;
}
// To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
if (err.code === "ENOENT") {
throw new Error("EACCES: permission denied, mkdir \"" + parentDir + "\"");
}
var caughtErr = ["EACCES", "EPERM", "EISDIR"].indexOf(err.code) > -1;
if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
throw err; // Throw if it's just the last created dir.
}
}
return curDir;
}, initDir);
}
function makeStatusDirs(filepath) {
try {
mkDirByPathSync(exports.homedir, filepath.replace(/\\/g, path.sep).replace(/\//g, path.sep));
return true;
}
catch (e) {
console.error("Error creating Application Insights status folder", e);
return false;
}
}
exports.makeStatusDirs = makeStatusDirs;
function renameCurrentFile(filepath, filename, callback) {
var fullpath = path.join(filepath, filename);
var basename = path.basename(filename, path.extname(filename));
var stats = fs.stat(fullpath, function (statsErr, stats) {
if (statsErr) {
return callback(statsErr);
}
var createDate = new Date(stats.birthtime);
var destfilename = basename + "-" +
createDate.toISOString().replace(/[T:\.]/g, "_").replace("Z", "") +
path.extname(filename) + ".old";
var destfullpath = path.join(filepath, destfilename);
fs.rename(fullpath, destfullpath, function (renameErr) {
if (typeof callback === "function") {
callback(renameErr, destfullpath);
}
});
});
}
exports.renameCurrentFile = renameCurrentFile;
//# sourceMappingURL=FileHelpers.js.map
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
import * as DataModel from "./DataModel";
export declare class NoopLogger implements DataModel.AgentLogger {
log(message?: any, ...optional: any[]): void;
error(message?: any, ...optional: any[]): void;
}
+21
View File
@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var NoopLogger = (function () {
function NoopLogger() {
}
NoopLogger.prototype.log = function (message) {
var optional = [];
for (var _i = 1; _i < arguments.length; _i++) {
optional[_i - 1] = arguments[_i];
}
};
NoopLogger.prototype.error = function (message) {
var optional = [];
for (var _i = 1; _i < arguments.length; _i++) {
optional[_i - 1] = arguments[_i];
}
};
return NoopLogger;
}());
exports.NoopLogger = NoopLogger;
//# sourceMappingURL=NoopLogger.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"NoopLogger.js","sourceRoot":"","sources":["../../Bootstrap/NoopLogger.ts"],"names":[],"mappings":";;AAGA;IAAA;IAKA,CAAC;IAJG,wBAAG,GAAH,UAAI,OAAa;QAAE,kBAAkB;aAAlB,UAAkB,EAAlB,qBAAkB,EAAlB,IAAkB;YAAlB,iCAAkB;;IACrC,CAAC;IACD,0BAAK,GAAL,UAAM,OAAa;QAAE,kBAAkB;aAAlB,UAAkB,EAAlB,qBAAkB,EAAlB,IAAkB;YAAlB,iCAAkB;;IACvC,CAAC;IACL,iBAAC;AAAD,CAAC,AALD,IAKC;AALY,gCAAU","sourcesContent":["import * as DataModel from \"./DataModel\";\r\nimport { FileWriter } from \"./FileWriter\";\r\n\r\nexport class NoopLogger implements DataModel.AgentLogger {\r\n log(message?: any, ...optional: any[]): void {\r\n }\r\n error(message?: any, ...optional: any[]): void {\r\n }\r\n}\r\n"]}
+3
View File
@@ -0,0 +1,3 @@
import * as types from "../applicationinsights";
declare var appInsights: typeof types;
export = appInsights;
+14
View File
@@ -0,0 +1,14 @@
"use strict";
var StatusLogger_1 = require("./StatusLogger");
var DiagnosticLogger_1 = require("./DiagnosticLogger");
var NoopLogger_1 = require("./NoopLogger");
var appInsightsLoader = require("./Default");
appInsightsLoader.setUsagePrefix("alr_"); // App Services Linux Attach
// Set Status.json logger
appInsightsLoader.setStatusLogger(new StatusLogger_1.StatusLogger(new NoopLogger_1.NoopLogger()));
// Set Attach Diagnostic Logger
appInsightsLoader.setLogger(new DiagnosticLogger_1.DiagnosticLogger(new NoopLogger_1.NoopLogger()));
// Start the SDK
var appInsights = appInsightsLoader.setupAndStart();
module.exports = appInsights;
//# sourceMappingURL=Oryx.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Oryx.js","sourceRoot":"","sources":["../../Bootstrap/Oryx.ts"],"names":[],"mappings":";AACA,+CAA8C;AAC9C,uDAAsD;AACtD,2CAA0C;AAC1C,6CAAgD;AAEhD,iBAAiB,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,4BAA4B;AAEtE,yBAAyB;AACzB,iBAAiB,CAAC,eAAe,CAAC,IAAI,2BAAY,CAAC,IAAI,uBAAU,EAAE,CAAC,CAAC,CAAC;AAEtE,+BAA+B;AAC/B,iBAAiB,CAAC,SAAS,CAAC,IAAI,mCAAgB,CAAC,IAAI,uBAAU,EAAE,CAAC,CAAC,CAAC;AAEpE,gBAAgB;AAChB,IAAI,WAAW,GAAG,iBAAiB,CAAC,aAAa,EAAE,CAAC;AAEpD,iBAAS,WAAW,CAAC","sourcesContent":["import * as types from \"../applicationinsights\"; // needed but unused\r\nimport { StatusLogger } from \"./StatusLogger\";\r\nimport { DiagnosticLogger } from \"./DiagnosticLogger\";\r\nimport { NoopLogger } from \"./NoopLogger\";\r\nimport appInsightsLoader = require(\"./Default\");\r\n\r\nappInsightsLoader.setUsagePrefix(\"alr_\"); // App Services Linux Attach\r\n\r\n// Set Status.json logger\r\nappInsightsLoader.setStatusLogger(new StatusLogger(new NoopLogger()));\r\n\r\n// Set Attach Diagnostic Logger\r\nappInsightsLoader.setLogger(new DiagnosticLogger(new NoopLogger()));\r\n\r\n// Start the SDK\r\nvar appInsights = appInsightsLoader.setupAndStart();\r\n\r\nexport = appInsights;\r\n"]}
+19
View File
@@ -0,0 +1,19 @@
import * as DataModel from "./DataModel";
export interface StatusContract {
AgentInitializedSuccessfully: boolean;
Reason?: string;
SDKPresent: boolean;
AppType: string;
MachineName: string;
PID: string;
SdkVersion: string;
Ikey: string;
}
export declare class StatusLogger {
_writer: DataModel.AgentLogger;
static readonly DEFAULT_FILE_PATH: string;
static readonly DEFAULT_FILE_NAME: string;
static readonly DEFAULT_STATUS: StatusContract;
constructor(_writer?: DataModel.AgentLogger);
logStatus(data: StatusContract, cb?: (err: Error) => void): void;
}
+43
View File
@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var os = require("os");
var path = require("path");
var fs = require("fs");
var FileWriter_1 = require("./FileWriter");
function readPackageVersion() {
var packageJsonPath = path.resolve(__dirname, "../../package.json");
try {
var packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
if (packageJson && typeof packageJson.version === "string") {
return packageJson.version;
}
}
catch (e) { }
return "unknown";
}
var StatusLogger = (function () {
function StatusLogger(_writer) {
if (_writer === void 0) { _writer = console; }
this._writer = _writer;
}
StatusLogger.prototype.logStatus = function (data, cb) {
if (typeof cb === "function" && this._writer instanceof FileWriter_1.FileWriter) {
this._writer.callback = cb;
}
this._writer.log(data);
};
StatusLogger.DEFAULT_FILE_PATH = path.join(FileWriter_1.homedir, "status");
StatusLogger.DEFAULT_FILE_NAME = "status_" + os.hostname() + "_" + process.pid + ".json";
StatusLogger.DEFAULT_STATUS = {
AgentInitializedSuccessfully: false,
SDKPresent: false,
Ikey: "unknown",
AppType: "node.js",
SdkVersion: readPackageVersion(),
MachineName: os.hostname(),
PID: String(process.pid)
};
return StatusLogger;
}());
exports.StatusLogger = StatusLogger;
//# sourceMappingURL=StatusLogger.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"StatusLogger.js","sourceRoot":"","sources":["../../Bootstrap/StatusLogger.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,uBAAyB;AACzB,2BAA6B;AAC7B,uBAAyB;AAEzB,2CAAmD;AAanD;IACI,IAAI,eAAe,GAAG,IAAI,CAAC,OAA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AC;KAC3B,CAAA;IAUL,mBAAC;CAAA,AArBD,IAqBC;AArBY,oCAAY","sourcesContent":["\"use strict\";\r\n\r\nimport * as os from \"os\";\r\nimport * as path from \"path\";\r\nimport * as fs from \"fs\";\r\nimport * as DataModel from \"./DataModel\";\r\nimport { FileWriter, homedir } from \"./FileWriter\";\r\n\r\nexport interface StatusContract {\r\n AgentInitializedSuccessfully: boolean;\r\n Reason?: string;\r\n SDKPresent: boolean;\r\n AppType: string;\r\n MachineName: string;\r\n PID: string;\r\n SdkVersion: string;\r\n Ikey: string;\r\n}\r\n\r\nfunction readPackageVersion() {\r\n let packageJsonPath = path.resolve(__dirname, \"../../package.json\");\r\n try {\r\n let packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\r\n if (packageJson && typeof packageJson.version === \"string\") {\r\n return packageJson.version;\r\n }\r\n } catch (e) { }\r\n return \"unknown\";\r\n}\r\n\r\nexport class StatusLogger {\r\n public static readonly DEFAULT_FILE_PATH: string = path.join(homedir, \"status\");\r\n public static readonly DEFAULT_FILE_NAME: string = `status_${os.hostname()}_${process.pid}.json`;\r\n public static readonly DEFAULT_STATUS: StatusContract = {\r\n AgentInitializedSuccessfully: false,\r\n SDKPresent: false,\r\n Ikey: \"unknown\",\r\n AppType: \"node.js\",\r\n SdkVersion: readPackageVersion(),\r\n MachineName: os.hostname(),\r\n PID: String(process.pid)\r\n }\r\n\r\n constructor(public _writer: DataModel.AgentLogger = console) {}\r\n\r\n public logStatus(data: StatusContract, cb?: (err: Error) => void) {\r\n if (typeof cb === \"function\" && this._writer instanceof FileWriter) {\r\n this._writer.callback = cb;\r\n }\r\n this._writer.log(data);\r\n }\r\n}\r\n"]}