Skip to content

Commit

Permalink
JSON configuration support (#875)
Browse files Browse the repository at this point in the history
* Allow auto tracking for not default telemetry clients

* Fixing tests

* Update

* Adding default config file

* Removing auto tracking changes

* Removing updates in readme, will update when release is ready

* Typo
  • Loading branch information
hectorhdzg authored Dec 7, 2021
1 parent 68d7012 commit 3190c80
Show file tree
Hide file tree
Showing 22 changed files with 671 additions and 3,301 deletions.
8 changes: 7 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,11 @@
"**/*.d.ts": true,
"out/": true
},
"typescript.tsdk": "./node_modules/typescript/lib"
"typescript.tsdk": "./node_modules/typescript/lib",
"markdownlint.config": {
"MD028": false,
"MD025": {
"front_matter_title": ""
}
}
}
4 changes: 2 additions & 2 deletions AutoCollection/HeartBeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ class HeartBeat {
this._client = client;
}

public enable(isEnabled: boolean, config?: Config) {
public enable(isEnabled: boolean) {
this._isEnabled = isEnabled;
if (this._isEnabled && !this._isInitialized) {
this._isInitialized = true;
}

if (isEnabled) {
if (!this._handle) {
this._handle = setInterval(() => this.trackHeartBeat(config, () => { }), this._collectionInterval);
this._handle = setInterval(() => this.trackHeartBeat(this._client.config, () => { }), this._collectionInterval);
this._handle.unref(); // Allow the app to terminate even while this loop is going on
}
} else {
Expand Down
16 changes: 8 additions & 8 deletions AutoCollection/NativePerformance.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import TelemetryClient= require("../Library/TelemetryClient");
import TelemetryClient = require("../Library/TelemetryClient");
import Constants = require("../Declarations/Constants");
import Config = require("../Library/Config");
import Context = require("../Library/Context");
import Logging= require("../Library/Logging");
import { IJsonConfig } from "../Library/IJsonConfig";
import Logging = require("../Library/Logging");
import { IBaseConfig } from "../Declarations/Interfaces";

/**
* Interface which defines which specific extended metrics should be disabled
Expand Down Expand Up @@ -111,10 +110,11 @@ export class AutoCollectNativePerformance {
* @private
* @static
* @param {(boolean | IDisabledExtendedMetrics)} collectExtendedMetrics
* @param {(IBaseConfig)} customConfig
* @returns {(boolean | IDisabledExtendedMetrics)}
* @memberof AutoCollectNativePerformance
*/
public static parseEnabled(collectExtendedMetrics: boolean | IDisabledExtendedMetrics, customConfig: IJsonConfig ): { isEnabled: boolean, disabledMetrics: IDisabledExtendedMetrics } {
public static parseEnabled(collectExtendedMetrics: boolean | IDisabledExtendedMetrics, customConfig: IBaseConfig): { isEnabled: boolean, disabledMetrics: IDisabledExtendedMetrics } {
const disableAll = customConfig.disableAllExtendedMetrics;
const individualOptOuts = customConfig.extendedMetricDisablers;

Expand All @@ -135,19 +135,19 @@ export class AutoCollectNativePerformance {

// case 2a: collectExtendedMetrics is an object, overwrite existing ones if they exist
if (typeof collectExtendedMetrics === "object") {
return {isEnabled: true, disabledMetrics: {...collectExtendedMetrics, ...disabledMetrics}};
return { isEnabled: true, disabledMetrics: { ...collectExtendedMetrics, ...disabledMetrics } };
}

// case 2b: collectExtendedMetrics is a boolean, set disabledMetrics as is
return {isEnabled: collectExtendedMetrics, disabledMetrics};
return { isEnabled: collectExtendedMetrics, disabledMetrics };
}

// case 4: no env vars set, input arg is a boolean, RETURN with isEnabled=collectExtendedMetrics, disabledMetrics={}
if (typeof collectExtendedMetrics === "boolean") {
return { isEnabled: collectExtendedMetrics, disabledMetrics: {} };
} else { // use else so we don't need to force typing on collectExtendedMetrics
// case 5: no env vars set, input arg is object, RETURN with isEnabled=true, disabledMetrics=collectExtendedMetrics
return { isEnabled: true, disabledMetrics: collectExtendedMetrics};
return { isEnabled: true, disabledMetrics: collectExtendedMetrics };
}
}

Expand Down
4 changes: 2 additions & 2 deletions AutoCollection/diagnostic-channel/initialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ import { AsyncScopeManager } from "../AsyncHooksScopeManager";
import Logging = require("../../Library/Logging");
import { JsonConfig } from "../../Library/JsonConfig";

export const IsInitialized = !JsonConfig.getJsonConfig().noDiagnosticChannel;
export const IsInitialized = !JsonConfig.getInstance().noDiagnosticChannel;
const TAG = "DiagnosticChannel";

if (IsInitialized) {
const publishers: typeof DiagChannelPublishers = require("diagnostic-channel-publishers");
const individualOptOuts: string = JsonConfig.getJsonConfig().noPatchModules;
const individualOptOuts: string = JsonConfig.getInstance().noPatchModules;
const unpatchedModules = individualOptOuts.split(",");
const modules: {[key: string] : any} = {
bunyan: publishers.bunyan,
Expand Down
2 changes: 1 addition & 1 deletion Bootstrap/Default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ let _logger: DiagnosticLogger = new DiagnosticLogger(console);
let _statusLogger: StatusLogger = new StatusLogger(console);

// Env var local constants
const _setupString = JsonConfig.getJsonConfig().connectionString || process.env.APPINSIGHTS_INSTRUMENTATIONKEY;
const _setupString = JsonConfig.getInstance().connectionString || process.env.APPINSIGHTS_INSTRUMENTATIONKEY;
const forceStart = process.env.APPLICATIONINSIGHTS_FORCE_START === "true";

// Other local constants
Expand Down
113 changes: 52 additions & 61 deletions Library/IJsonConfig.ts → Declarations/Interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
/**
* Configuration settings
* @export
* @interface IJsonConfig
*/

import { DistributedTracingModes } from "../applicationinsights";
import { IDisabledExtendedMetrics } from "../AutoCollection/NativePerformance";
import http = require('http');
import https = require('https');
export interface IJsonConfig {
connectionString?: string;
import azureCore = require("@azure/core-http");
import { DistributedTracingModes } from "../applicationinsights";
import { IDisabledExtendedMetrics } from "../AutoCollection/NativePerformance";


export interface IBaseConfig {
/** Connection String used to send telemetry payloads to */
connectionString: string;
/** The ingestion endpoint to send telemetry payloads to */
endpointUrl: string;
/** The maximum number of telemetry items to include in a payload to the ingestion endpoint (Default 250) */
Expand All @@ -28,87 +26,71 @@ export interface IJsonConfig {
proxyHttpUrl: string;
/** A proxy server for SDK HTTPS traffic (Optional, Default pulled from `https_proxy` environment variable) */
proxyHttpsUrl: string;
/** An http.Agent to use for SDK HTTP traffic (Optional, Default undefined) */
httpAgent: http.Agent;
/** An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined) */
httpsAgent: https.Agent;
/** Disable including legacy headers in outgoing requests, x-ms-request-id */
ignoreLegacyHeaders?: boolean;
ignoreLegacyHeaders: boolean;
/**
* Sets the distributed tracing modes. If W3C mode is enabled, W3C trace context
* headers (traceparent/tracestate) will be parsed in all incoming requests, and included in outgoing
* requests. In W3C mode, existing back-compatibility AI headers will also be parsed and included.
* Enabling W3C mode will not break existing correlation with other Application Insights instrumented
* services. Default=AI
*/
distributedTracingMode?: DistributedTracingModes;

distributedTracingMode: DistributedTracingModes;
/**
* Sets the state of console
* if true logger activity will be sent to Application Insights
*/
enableAutoCollectExternalLoggers?: boolean;

enableAutoCollectExternalLoggers: boolean;
/**
* Sets the state of logger tracking (enabled by default for third-party loggers only)
* if true, logger autocollection will include console.log calls (default false)
*/
enableAutoCollectConsole?: boolean;

enableAutoCollectConsole: boolean;
/**
* Sets the state of exception tracking (enabled by default)
* if true uncaught exceptions will be sent to Application Insights
*/
enableAutoCollectExceptions?: boolean;

enableAutoCollectExceptions: boolean;
/**
* Sets the state of performance tracking (enabled by default)
* if true performance counters will be collected every second and sent to Application Insights
*/
enableAutoCollectPerformance?: boolean;

enableAutoCollectPerformance: boolean;
/**
* Sets the state of performance tracking (enabled by default)
* if true, extended metrics counters will be collected every minute and sent to Application Insights
*/
enableAutoCollectExtendedMetrics?: boolean | IDisabledExtendedMetrics;

enableAutoCollectExtendedMetrics: boolean | IDisabledExtendedMetrics;
/**
* Sets the state of pre aggregated metrics tracking (enabled by default)
* if true pre aggregated metrics will be collected every minute and sent to Application Insights
*/
enableAutoCollectPreAggregatedMetrics?: boolean;

enableAutoCollectPreAggregatedMetrics: boolean;
/**
* Sets the state of request tracking (enabled by default)
* if true HeartBeat metric data will be collected every 15 mintues and sent to Application Insights
* if true HeartBeat metric data will be collected every 15 minutes and sent to Application Insights
*/
enableAutoCollectHeartbeat?: boolean;

enableAutoCollectHeartbeat: boolean;
/**
* Sets the state of request tracking (enabled by default)
* if true requests will be sent to Application Insights
*/
enableAutoCollectRequests?: boolean;

enableAutoCollectRequests: boolean;
/**
* Sets the state of dependency tracking (enabled by default)
* if true dependencies will be sent to Application Insights
*/
enableAutoCollectDependencies?: boolean;

enableAutoCollectDependencies: boolean;
/**
* Sets the state of automatic dependency correlation (enabled by default)
* if true dependencies will be correlated with requests
*/
enableAutoDependencyCorrelation?: boolean;

enableAutoDependencyCorrelation: boolean;
/**
* Sets the state of automatic dependency correlation (enabled by default)
* if true, forces use of experimental async_hooks module to provide correlation. If false, instead uses only patching-based techniques. If left blank, the best option is chosen for you based on your version of Node.js.
*/
enableUseAsyncHooks?: boolean;

enableUseAsyncHooks: boolean;
/**
* Enable or disable disk-backed retry caching to cache events when client is offline (enabled by default)
* Note that this method only applies to the default client. Disk-backed retry caching is disabled by default for additional clients.
Expand All @@ -118,62 +100,71 @@ export interface IJsonConfig {
* enableResendInterval The wait interval for resending cached events.
* enableMaxBytesOnDisk The maximum size (in bytes) that the created temporary directory for cache events can grow to, before caching is disabled.
*/
enableUseDiskRetryCaching?: boolean;
enableResendInterval?: number;
enableMaxBytesOnDisk?: number;

enableUseDiskRetryCaching: boolean;
enableResendInterval: number;
enableMaxBytesOnDisk: number;
/**
* Enables debug and warning logging for AppInsights itself.
* if true, enables debug logging
*/
enableInternalDebugLogging?: boolean;

enableInternalDebugLogging: boolean;
/**
* Enables debug and warning logging for AppInsights itself.
* if true, enables warning logging
*/
enableInternalWarningLogging?: boolean;

enableInternalWarningLogging: boolean;
/**
* Enables communication with Application Insights Live Metrics.
* if true, enables communication with the live metrics service
*/
enableSendLiveMetrics?: boolean;

enableSendLiveMetrics: boolean;
/**
* Disable all environment variables set
*/
disableAllExtendedMetrics?: boolean;

disableAllExtendedMetrics: boolean;
/**
* Disable individual environment variables set. eg. "extendedMetricDisablers": "..."
*/
extendedMetricDisablers?: string;

extendedMetricDisablers: string;
/**
* Disable Statsbeat
*/
disableStatsbeat?: boolean;
disableStatsbeat: boolean;
/**
* Live Metrics custom host
*/
quickPulseHost: string;
}

export interface IEnvironmentConfig {
/**
* In order to track context across asynchronous calls,
* some changes are required in third party libraries such as mongodb and redis.
* By default ApplicationInsights will use diagnostic-channel-publishers to monkey-patch some of these libraries.
* This property is to disable the feature.
* Note that by setting this flag, events may no longer be correctly associated with the right operation.
*/
noDiagnosticChannel?: boolean;

noDiagnosticChannel: boolean;
/**
* Disable individual monkey-patches.
* Set `noPatchModules` to a comma separated list of packages to disable.
* e.g. `"noPatchModules": "console,redis"` to avoid patching the console and redis packages.
* The following modules are available: `azuresdk, bunyan, console, mongodb, mongodb-core, mysql, redis, winston, pg`, and `pg-pool`.
*/
noPatchModules?: string;

noPatchModules: string;
/**
* HTTPS without a passed in agent
*/
noHttpAgentKeepAlive?: boolean;
}
noHttpAgentKeepAlive: boolean;
}

export interface IJsonConfig extends IBaseConfig, IEnvironmentConfig { };

export interface IConfig extends IBaseConfig {
/** An http.Agent to use for SDK HTTP traffic (Optional, Default undefined) */
httpAgent: http.Agent;
/** An https.Agent to use for SDK HTTPS traffic (Optional, Default undefined) */
httpsAgent: https.Agent;
/** AAD TokenCredential to use to authenticate the app */
aadTokenCredential?: azureCore.TokenCredential;
}
Loading

0 comments on commit 3190c80

Please sign in to comment.