### Install dependencies Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/CONTRIBUTING.md Install all necessary project dependencies using npm. ```bash npm install ``` -------------------------------- ### Initialize Application Insights SDK Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Use this method to set up and start the Application Insights SDK with your connection string. Ensure you replace '' with your actual connection string. ```javascript let applicationinsights = require("applicationinsights"); appinsights.setup("").start(); ``` -------------------------------- ### Clone the repository Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/CONTRIBUTING.md Clone your forked repository locally to start making changes. ```bash git clone https://github.com//ApplicationInsights-node.js ``` -------------------------------- ### Start Application Insights Telemetry Collection Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Call `appInsights.start()` to begin automatically collecting and sending telemetry data to Azure Monitor. This should be done after setup. ```javascript appInsights.start(); ``` -------------------------------- ### Initialize and Configure Application Insights SDK Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Use this snippet to initialize the SDK with a connection string and configure various auto-collection features. All configuration must be done before calling `start()`. ```javascript let appInsights = require("applicationinsights"); appInsights.setup("") .setAutoCollectRequests(true) .setAutoCollectPerformance(true, true) .setAutoCollectExceptions(true) .setAutoCollectDependencies(true) .setAutoCollectConsole(true, false) .setAutoCollectPreAggregatedMetrics(true) .setSendLiveMetrics(false) .setInternalLogging(false, true) .enableWebInstrumentation(false) .start(); ``` -------------------------------- ### Install Application Insights SDK Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Add the Application Insights Node.js SDK to your project's dependencies. This is a prerequisite for using the SDK. ```bash npm install --save applicationinsights ``` -------------------------------- ### Initialize Application Insights SDK Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Initializes the SDK with a connection string and enables automatic collection of requests, performance counters, exceptions, dependencies, console logs, and live metrics. Call `start()` after configuration. ```javascript const appInsights = require("applicationinsights"); // Initialize with connection string from environment or parameter appInsights.setup("InstrumentationKey=your-key;IngestionEndpoint=https://dc.services.visualstudio.com") .setAutoCollectRequests(true) // Track incoming HTTP requests .setAutoCollectPerformance(true, true) // Collect performance counters .setAutoCollectExceptions(true) // Capture uncaught exceptions .setAutoCollectDependencies(true) // Track outgoing HTTP/database calls .setAutoCollectConsole(true, false) // Track third-party loggers (winston/bunyan) .setAutoCollectPreAggregatedMetrics(true) .setSendLiveMetrics(true) // Enable live metrics stream .setInternalLogging(false, true) // Enable warning logging .start(); // Access the default client for manual tracking const client = appInsights.defaultClient; console.log("Application Insights initialized"); ``` -------------------------------- ### Application Insights Configuration JSON Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Example of a configuration file for Application Insights. These settings apply to all TelemetryClients. Ensure the configuration is complete before calling appInsights.start(). ```json { "samplingPercentage": 80, "enableAutoCollectExternalLoggers": true, "enableAutoCollectExceptions": true, "enableSendLiveMetrics": true, ... } ``` -------------------------------- ### Configure TelemetryClient Options Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Configures advanced TelemetryClient options such as sampling percentage, proxy settings, batching intervals, disk retry caching, and Azure AD authentication. Ensure `start()` is called after configuration. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING"); const client = appInsights.defaultClient; // Configure sampling to reduce data volume client.config.samplingPercentage = 50; // Only send 50% of telemetry // Configure proxy for corporate networks client.config.proxyHttpUrl = "http://proxy.company.com:8080"; client.config.proxyHttpsUrl = "https://proxy.company.com:8080"; // Configure batching behavior client.config.maxBatchIntervalMs = 15000; // Send every 15 seconds // Enable disk retry caching for offline scenarios client.config.enableUseDiskRetryCaching = true; // Configure Azure AD authentication const { DefaultAzureCredential } = require("@azure/identity"); client.config.aadTokenCredential = new DefaultAzureCredential(); // Must call start() after configuration appInsights.start(); ``` -------------------------------- ### Configure Application Insights via Environment Variables Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Sets environment variables to configure the SDK, allowing for flexible deployment without code changes. The `setup()` function will automatically detect and use these variables. A JSON configuration file can also be specified via `APPLICATIONINSIGHTS_CONFIGURATION_FILE`. ```javascript // Set environment variables before requiring applicationinsights process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=your-key;IngestionEndpoint=https://dc.services.visualstudio.com"; process.env.APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL = "WARN"; process.env.APPLICATIONINSIGHTS_LOG_DESTINATION = "file+console"; process.env.APPLICATIONINSIGHTS_LOGDIR = "/var/log/appinsights"; const appInsights = require("applicationinsights"); // Setup will automatically use environment variables appInsights.setup().start(); // Alternatively, use a custom JSON configuration file process.env.APPLICATIONINSIGHTS_CONFIGURATION_FILE = "/etc/appinsights/config.json"; // JSON config file example (applicationinsights.json): // { // "samplingPercentage": 80, // "enableAutoCollectExceptions": true, // "enableAutoCollectPerformance": true, // "enableSendLiveMetrics": true, // "maxBatchIntervalMs": 15000 // } ``` -------------------------------- ### Express.js Integration with Application Insights Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Complete example of integrating Application Insights with an Express.js application, including auto-collection and custom event tracking. Initialize the SDK before other requires. ```javascript const appInsights = require("applicationinsights"); // Initialize BEFORE other requires appInsights.setup("YOUR_CONNECTION_STRING") .setAutoCollectRequests(true) .setAutoCollectDependencies(true) .setAutoCollectExceptions(true) .setAutoCollectPerformance(true) .setAutoCollectConsole(true, true) // Include console.log .setSendLiveMetrics(true) .start(); const client = appInsights.defaultClient; // Now require Express const express = require("express"); const app = express(); // Custom middleware to add properties to all telemetry app.use((req, res, next) => { // Add custom properties that will be included in telemetry client.commonProperties = { environment: process.env.NODE_ENV, version: process.env.APP_VERSION }; next(); }); // Route with manual event tracking app.post("/api/orders", async (req, res) => { const startTime = Date.now(); try { // Process order... const orderId = "ORD-" + Date.now(); // Track business event client.trackEvent({ name: "OrderCreated", properties: { orderId, customerId: req.body.customerId, itemCount: req.body.items?.length.toString() }, measurements: { orderTotal: req.body.total, processingTime: Date.now() - startTime } }); res.json({ orderId, status: "created" }); } catch (error) { client.trackException({ exception: error, properties: { route: "/api/orders" } }); res.status(500).json({ error: "Order creation failed" }); } }); // Error handler app.use((err, req, res, next) => { client.trackException({ exception: err }); res.status(500).send("Something broke!"); }); // Graceful shutdown const server = app.listen(3000, () => { console.log("Server running on port 3000"); client.trackEvent({ name: "ServerStarted" }); }); process.on("SIGTERM", async () => { client.trackEvent({ name: "ServerStopping" }); await client.flush(); server.close(() => process.exit(0)); }); ``` -------------------------------- ### Track Application Availability Tests with Node.js Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Use `trackAvailability` to record the results of synthetic tests that monitor your application's uptime and responsiveness. Includes examples for both successful and failed tests, as well as a custom monitoring function. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Track successful availability test client.trackAvailability({ id: "test-run-" + Date.now(), name: "Homepage Health Check", duration: 250, success: true, runLocation: "East US", message: "All checks passed", properties: { testType: "URL Ping", endpoint: "https://www.example.com" }, measurements: { responseTime: 250, contentLength: 15000 } }); // Track failed availability test client.trackAvailability({ id: "test-run-" + Date.now(), name: "API Endpoint Check", duration: 30000, success: false, runLocation: "West Europe", message: "Connection timeout after 30 seconds", properties: { testType: "Multi-step", endpoint: "https://api.example.com/health", errorCode: "ETIMEDOUT" } }); // Custom availability monitoring function async function runAvailabilityTest(testName, url) { const startTime = Date.now(); try { const response = await fetch(url); const duration = Date.now() - startTime; client.trackAvailability({ id: `${testName}-${startTime}`, name: testName, duration: duration, success: response.ok, runLocation: process.env.REGION || "Local", message: response.ok ? "OK" : `HTTP ${response.status}`, properties: { url, statusCode: response.status.toString() } }); } catch (error) { client.trackAvailability({ id: `${testName}-${startTime}`, name: testName, duration: Date.now() - startTime, success: false, runLocation: process.env.REGION || "Local", message: error.message }); } } ``` -------------------------------- ### Enable Web Instrumentation for Browser Integration Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Enable automatic injection of the Application Insights JavaScript SDK into server-rendered HTML pages. This can be configured using setup or environment variables. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING") .enableWebInstrumentation(true) // Optionally use a different connection string for browser telemetry .enableWebInstrumentation(true, "BROWSER_CONNECTION_STRING") .start(); // Environment variable alternative process.env.APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_ENABLED = "true"; process.env.APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_CONNECTION_STRING = "BROWSER_CONNECTION_STRING"; process.env.APPLICATIONINSIGHTS_WEB_INSTRUMENTATION_SOURCE = "https://js.monitor.azure.com/scripts/b/ai.2.min.js"; // Web instrumentation automatically injects into HTML responses when: // - Response has status code 200 // - Response method is GET // - Response has Content-Type: text/html // - Response contains both and tags ``` -------------------------------- ### Frontend Setup for CORS Correlation Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Configure the Application Insights web SDK with `enableCorsCorrelation: true` to automatically include correlation headers in outgoing HTTP requests from the frontend. ```javascript const appInsights = new ApplicationInsights({ config: { connectionString: "your-connection-string", enableCorsCorrelation: true // Important for cross-domain correlation } }); appInsights.loadAppInsights(); ``` -------------------------------- ### Track Page Views with Node.js Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Use `trackPageView` to record user navigation within your application, essential for server-side rendered or hybrid applications. Examples cover basic page view tracking, including referrer information, and an Express.js middleware. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Track a page view client.trackPageView({ id: "page-view-" + Date.now(), name: "Product Details Page", url: "https://www.example.com/products/widget-123", duration: 1500, properties: { productId: "widget-123", category: "Electronics", referrer: "https://www.google.com" }, measurements: { loadTime: 1500, domContentLoaded: 800, firstContentfulPaint: 500 } }); // Track page view with referrer client.trackPageView({ id: "pv-" + Date.now(), name: "Checkout Page", url: "https://www.example.com/checkout", referredUri: "https://www.example.com/cart", duration: 2000, properties: { cartItemCount: "3", cartTotal: "149.99" } }); // Express.js middleware example function trackPageViewMiddleware(req, res, next) { const startTime = Date.now(); res.on("finish", () => { if (res.statusCode === 200 && req.accepts("html")) { client.trackPageView({ id: `pv-${startTime}`, name: req.path, url: req.originalUrl, duration: Date.now() - startTime, properties: { userAgent: req.get("User-Agent"), method: req.method } }); } }); next(); } ``` -------------------------------- ### Enable Debug Logging for Application Insights Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Configure Application Insights Node.js SDK to enable internal debug and warning logging, and to automatically collect console logs as Trace telemetry. This setup requires a connection string and can be enhanced with environment variables for log destination and directory. ```javascript let appInsights = require("applicationinsights"); appInsights.setup("") .setInternalLogging(true, true) // Enable both debug and warning logging .setAutoCollectConsole(true, true) // Generate Trace telemetry for winston/bunyan and console logs .start(); ``` ```javascript process.env.APPLICATIONINSIGHTS_LOG_DESTINATION = "file"; process.env.APPLICATIONINSIGHTS_LOGDIR = "C:/applicationinsights/logs" // Application Insights SDK setup.... ``` -------------------------------- ### Track Custom Telemetry with Application Insights Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Use this snippet to track various custom telemetry events like custom events, exceptions, metrics, traces, dependencies, requests, and availability. Ensure Application Insights is set up and started before calling these methods. ```javascript let appInsights = require("applicationinsights"); appInsights.setup().start(); // assuming connection string is in environment variables. start() can be omitted to disable any non-custom data let client = appInsights.defaultClient; client.trackEvent({name: "my custom event", properties: {customProperty: "custom property value"}}); client.trackException({exception: new Error("handled exceptions can be logged with this method")}); client.trackMetric({name: "custom metric", value: 3}); client.trackTrace({message: "trace message"}); client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:231, resultCode:0, success: true, dependencyTypeName: "ZSQL"}); client.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true}); client.trackAvailability({id: "123456789abcdefghijklmnopqrstuvw", name: "availalaibility-test-name", duration: 1000, success: true, runLocation: "Japan East", message: "Passed"}) ``` ```javascript let http = require("http"); http.createServer( (req, res) => { client.trackNodeHttpRequest({request: req, response: res}); // Place at the beginning of your request handler }); ``` -------------------------------- ### Navigate to project directory Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/CONTRIBUTING.md Change your current directory to the cloned project folder. ```bash cd ApplicationInsights-node.js ``` -------------------------------- ### Build the project Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/CONTRIBUTING.md Compile the project's code using the build script. ```bash npm run build ``` -------------------------------- ### Create TelemetryClient with Constructor Options Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Instantiate a `TelemetryClient` with a connection string and optional configuration settings like `useGlobalProviders`. ```javascript const client = new appInsights.TelemetryClient(, { useGlobalProviders: false }); ``` -------------------------------- ### Configure Web Instrumentation with a Specific Connection String Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md To use a connection string different from the SDK initialization, provide it as the second argument to `enableWebInstrumentation()`. ```javascript appInsights.enableWebInstrumentation(true, "your-connection-string"); ``` -------------------------------- ### Run unit tests Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/CONTRIBUTING.md Execute the unit tests to verify individual components. ```bash npm run test ``` -------------------------------- ### Direct OpenTelemetry Integration with Azure Monitor Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Initialize Azure Monitor with OpenTelemetry options for advanced configuration, including custom processors and OTLP exporters. Ensure to set `connectionString` and configure desired instrumentation. ```javascript const { useAzureMonitor, shutdownAzureMonitor, flushAzureMonitor } = require("applicationinsights"); // Initialize with Azure Monitor OpenTelemetry options useAzureMonitor({ azureMonitorExporterOptions: { connectionString: "YOUR_CONNECTION_STRING" }, samplingRatio: 0.5, // 50% sampling enableAutoCollectExceptions: true, enableAutoCollectPerformance: true, instrumentationOptions: { http: { enabled: true }, azureSdk: { enabled: true }, mongoDb: { enabled: true }, mySql: { enabled: true }, postgreSql: { enabled: true }, redis: { enabled: true }, redis4: { enabled: true }, bunyan: { enabled: true }, winston: { enabled: true }, console: { enabled: false } }, // OTLP exporters for sending to additional backends otlpTraceExporterConfig: { enabled: true, url: "http://localhost:4318/v1/traces" }, otlpMetricExporterConfig: { enabled: true, url: "http://localhost:4318/v1/metrics" }, otlpLogExporterConfig: { enabled: true, url: "http://localhost:4318/v1/logs" } }); // Flush all pending telemetry await flushAzureMonitor(); // Graceful shutdown process.on("SIGTERM", async () => { await shutdownAzureMonitor(); process.exit(0); }); ``` -------------------------------- ### Configure Application Insights with Connection String Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Configure the SDK with your Application Insights connection string. You can either pass it directly or set it as an environment variable. ```javascript appInsights.setup('YOUR_CONNECTION_STRING'); ``` ```javascript appInsights.setup() ``` -------------------------------- ### Create Additional TelemetryClients Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Instantiate multiple TelemetryClient objects to send telemetry to different Application Insights resources or with distinct configurations. Ensure to use isolated providers for additional clients if needed. ```javascript const appInsights = require("applicationinsights"); // Initialize default client appInsights.setup("YOUR_CONNECTION_STRING").start(); // Create additional client for different resource const secondaryClient = new appInsights.TelemetryClient( "InstrumentationKey=different-key;IngestionEndpoint=https://dc.services.visualstudio.com", { useGlobalProviders: false } // Use isolated providers for this client ); // Track telemetry to different resources appInsights.defaultClient.trackEvent({ name: "PrimaryEvent" }); secondaryClient.trackEvent({ name: "SecondaryEvent" }); // Flush both clients await appInsights.defaultClient.flush(); await secondaryClient.flush(); ``` -------------------------------- ### Run back compatibility tests Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/CONTRIBUTING.md Run tests to check compatibility with older Node.js runtimes and TypeScript versions. ```bash npm run backcompattest ``` -------------------------------- ### Load Application Insights Library Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Load the Application Insights library as early as possible in your application's code. This ensures proper initialization before other packages are loaded. ```javascript let appInsights = require('applicationinsights'); ``` -------------------------------- ### Run functional tests Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/CONTRIBUTING.md Execute functional tests, which require Docker to be running. ```bash npm run functionaltest ``` -------------------------------- ### Specify Custom Configuration File Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Set the APPLICATIONINSIGHTS_CONFIGURATION_FILE environment variable to point to a custom JSON configuration file for Application Insights. ```javascript process.env.APPLICATIONINSIGHTS_CONFIGURATION_FILE = "C:/applicationinsights/config/customConfig.json" // Application Insights SDK setup.... ``` -------------------------------- ### Run Trace Tracking Performance Test Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/test/performanceTests/README.md Execute a performance test for tracking traces (logs) in Node.js. Ensure Application Insights is configured with a connection string. ```bash npm run perf-test:node -- TrackTraceTest --warmup 1 --iterations 1 --parallel 2 --duration 15 ``` -------------------------------- ### Configure Logging and Log Destination Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Set environment variables to control the Application Insights SDK's logging level and specify where logs should be sent. Logs can be directed to a file, the console, or both, with an option to configure a custom log directory. ```javascript process.env.APPLICATIONINSIGHTS_INSTRUMENTATION_LOGGING_LEVEL = "VERBOSE"; process.env.APPLICATIONINSIGHTS_LOG_DESTINATION = "file"; process.env.APPLICATIONINSIGHTS_LOGDIR = "C:/applicationinsights/logs"; // Application Insights SDK setup.... ``` -------------------------------- ### Set Client-Specific Configuration Properties Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Configure properties specific to a `TelemetryClient` instance by accessing its `config` object. ```javascript client.config.PROPERTYNAME = VALUE; ``` -------------------------------- ### Manage Correlation Context in Node.js Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Access and manage the current correlation context for distributed tracing. Use `startOperation` to initiate operations from incoming requests and `wrapWithCorrelationContext` to preserve context across asynchronous operations. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); // Get current correlation context const context = appInsights.getCorrelationContext(); if (context) { console.log("Operation ID:", context.operation.id); console.log("Parent ID:", context.operation.parentId); console.log("Operation Name:", context.operation.name); } // Start a new operation from incoming request const http = require("http"); http.createServer((req, res) => { // Start operation extracts trace context from headers const correlationContext = appInsights.startOperation(req, "ProcessRequest"); if (correlationContext) { console.log("Trace ID:", correlationContext.operation.id); console.log("Span ID:", correlationContext.operation.traceparent?.spanId); } res.writeHead(200); res.end("OK"); }).listen(3000); // Wrap async callbacks to maintain context async function processWithContext() { const context = appInsights.getCorrelationContext(); // Wrap callback to preserve context const wrappedCallback = appInsights.wrapWithCorrelationContext(() => { // This code runs with the original correlation context const currentContext = appInsights.getCorrelationContext(); console.log("Context preserved:", currentContext?.operation.id); }, context); // Execute later - context will be preserved setTimeout(wrappedCallback, 1000); } ``` -------------------------------- ### Run Dependency Tracking Performance Test Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/test/performanceTests/README.md Execute a performance test for tracking dependencies (spans) in Node.js. Ensure Application Insights is configured with a connection string. ```bash npm run perf-test:node -- TrackDependencyTest --warmup 1 --iterations 1 --parallel 2 --duration 15 ``` -------------------------------- ### Track Custom Numeric Metrics with Application Insights Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Use `trackMetric` to log custom numeric data. Supports simple values, aggregated values (count, min, max), and custom properties for filtering and analysis. Useful for KPIs and performance indicators. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Track a simple metric client.trackMetric({ name: "QueueLength", value: 42 }); ``` ```javascript // Track metric with properties for filtering client.trackMetric({ name: "OrderProcessingTime", value: 1250, properties: { region: "us-west", orderType: "express", paymentMethod: "creditcard" } }); ``` ```javascript // Track aggregated metrics client.trackMetric({ name: "APIResponseTime", value: 150, count: 100, // Number of samples min: 50, // Minimum value max: 500, // Maximum value properties: { endpoint: "/api/users", method: "GET" } }); ``` ```javascript // Example: Measure event loop delay function startMeasuringEventLoop() { let startTime = process.hrtime(); let sampleSum = 0; let sampleCount = 0; setInterval(() => { const elapsed = process.hrtime(startTime); startTime = process.hrtime(); sampleSum += elapsed[0] * 1e9 + elapsed[1]; sampleCount++; }, 0); setInterval(() => { if (sampleCount > 0) { const avgMs = Math.round(sampleSum / sampleCount / 1e6); client.trackMetric({ name: "EventLoopDelay", value: avgMs }); sampleSum = 0; sampleCount = 0; } }, 1000); } ``` -------------------------------- ### Configure Console Auto-Collection Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md By default, `setAutoCollectConsole` excludes `console.log`. Use `setAutoCollectConsole(true, true)` to include `console.log` calls. ```javascript appInsights.setup().setAutoCollectConsole(true, true); ``` -------------------------------- ### Track Custom Events with Properties and Measurements Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Use trackEvent to log custom business events, including user actions and application workflows. Events can be enriched with custom properties and numerical measurements. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Track a simple event client.trackEvent({ name: "UserLogin" }); // Track event with custom properties client.trackEvent({ name: "ItemPurchased", properties: { itemId: "SKU-12345", category: "Electronics", paymentMethod: "CreditCard", userId: "user-abc-123" }, measurements: { purchaseAmount: 299.99, quantity: 2, discountPercent: 10 } }); // Track event with timestamp client.trackEvent({ name: "OrderShipped", time: new Date("2024-01-15T10:30:00Z"), properties: { orderId: "ORD-789", carrier: "FedEx", trackingNumber: "123456789" } }); ``` -------------------------------- ### Track Exceptions with Severity and Properties Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Log handled exceptions using trackException to aid in debugging and error analysis. Specify severity levels (Error, Warning, Critical) and attach custom properties or measurements. ```javascript const appInsights = require("applicationinsights"); const { KnownSeverityLevel } = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Track a caught exception try { throw new Error("Database connection failed"); } catch (error) { client.trackException({ exception: error, properties: { operation: "DatabaseConnect", connectionString: "***masked***", retryCount: "3" }, measurements: { attemptDuration: 5000 }, severity: KnownSeverityLevel.Error }); } // Track exception with different severity levels client.trackException({ exception: new Error("Configuration warning: using default values"), severity: KnownSeverityLevel.Warning, properties: { configFile: "/etc/app/config.json", missingKeys: "database.timeout,cache.ttl" } }); // Track critical exception client.trackException({ exception: new Error("Payment processing system unavailable"), severity: KnownSeverityLevel.Critical, properties: { paymentGateway: "Stripe", affectedOrders: "15" } }); ``` -------------------------------- ### trackMetric - Custom Metrics API Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Track custom numeric metrics like performance indicators, business KPIs, and resource utilization. ```APIDOC ## trackMetric - Custom Metrics ### Description Track custom numeric metrics like performance indicators, business KPIs, and resource utilization. ### Method `client.trackMetric(metricData)` ### Parameters #### Request Body - **name** (string) - Required - The name of the metric. - **value** (number) - Required - The value of the metric. - **count** (number) - Optional - The number of samples for aggregated metrics. - **min** (number) - Optional - The minimum value for aggregated metrics. - **max** (number) - Optional - The maximum value for aggregated metrics. - **properties** (object) - Optional - Custom properties for filtering and segmentation. ### Request Example ```javascript client.trackMetric({ name: "QueueLength", value: 42 }); client.trackMetric({ name: "OrderProcessingTime", value: 1250, properties: { region: "us-west", orderType: "express" } }); client.trackMetric({ name: "APIResponseTime", value: 150, count: 100, min: 50, max: 500, properties: { endpoint: "/api/users", method: "GET" } }); ``` ``` -------------------------------- ### Configure Sampling Percentage Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md Set the samplingPercentage property on the Client config to control the amount of telemetry data sent to Application Insights. A value of 100 sends all data, while 0 sends none. Automatic correlation ensures data for a single request is included or excluded as a unit. ```javascript const appInsights = require("applicationinsights"); appInsights.setup(""); appInsights.defaultClient.config.samplingPercentage = 33; // 33% of all telemetry will be sent to Application Insights appInsights.start(); // Configuration must be complete before calling start() ``` -------------------------------- ### Track External Dependencies with Application Insights Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Use `trackDependency` to monitor calls to external services, databases, or APIs. Specify dependency type, target, data, duration, result code, and success status. Essential for understanding application performance bottlenecks and external service health. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Track HTTP dependency client.trackDependency({ name: "GET /external-api/data", dependencyTypeName: "HTTP", target: "external-api.example.com", data: "https://external-api.example.com/data?id=123", duration: 250, resultCode: "200", success: true, properties: { apiVersion: "v1", cacheHit: "false" } }); ``` ```javascript // Track database dependency client.trackDependency({ name: "SELECT users", dependencyTypeName: "SQL", target: "sql-server.database.windows.net", data: "SELECT * FROM users WHERE status = 'active'", duration: 45, resultCode: "0", success: true, properties: { database: "UserDB", rowsReturned: "150" } }); ``` ```javascript // Track Redis cache dependency client.trackDependency({ name: "GET user:123", dependencyTypeName: "Redis", target: "redis-cache.redis.cache.windows.net", data: "GET user:123", duration: 5, resultCode: "0", success: true }); ``` ```javascript // Track failed dependency client.trackDependency({ name: "POST /payment-gateway", dependencyTypeName: "HTTP", target: "payments.stripe.com", data: "https://payments.stripe.com/v1/charges", duration: 30000, resultCode: "504", success: false, properties: { errorMessage: "Gateway timeout", retryAttempt: "3" } }); ``` -------------------------------- ### Measure Event Loop Scheduling Delay Source: https://github.com/microsoft/applicationinsights-node.js/blob/main/README.md This utility uses `setInterval` to measure and report the event loop scheduling delay as a custom metric. It samples the delay and reports the average in milliseconds every second. ```javascript function startMeasuringEventLoop() { var startTime = process.hrtime(); var sampleSum = 0; var sampleCount = 0; // Measure event loop scheduling delay setInterval(() => { var elapsed = process.hrtime(startTime); startTime = process.hrtime(); sampleSum += elapsed[0] * 1e9 + elapsed[1]; sampleCount++; }, 0); // Report custom metric every second setInterval(() => { var samples = sampleSum; var count = sampleCount; sampleSum = 0; sampleCount = 0; if (count > 0) { var avgNs = samples / count; var avgMs = Math.round(avgNs / 1e6); client.trackMetric({name: "Event Loop Delay", value: avgMs}); } }, 1000); } ``` -------------------------------- ### trackDependency - External Dependency Tracking API Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Track calls to external services, databases, and APIs for dependency monitoring and performance analysis. ```APIDOC ## trackDependency - External Dependency Tracking ### Description Track calls to external services, databases, and APIs for dependency monitoring and performance analysis. ### Method `client.trackDependency(dependencyData)` ### Parameters #### Request Body - **name** (string) - Required - The name of the dependency (e.g., 'GET /external-api/data', 'SELECT users'). - **dependencyTypeName** (string) - Required - The type of the dependency (e.g., 'HTTP', 'SQL', 'Redis'). - **target** (string) - Optional - The target of the dependency (e.g., 'external-api.example.com', 'sql-server.database.windows.net'). - **data** (string) - Optional - The command or URL associated with the dependency. - **duration** (number) - Required - The duration of the dependency call in milliseconds. - **resultCode** (string) - Required - The result code of the dependency call. - **success** (boolean) - Required - Indicates if the dependency call was successful. - **properties** (object) - Optional - Custom properties for filtering and segmentation. ### Request Example ```javascript client.trackDependency({ name: "GET /external-api/data", dependencyTypeName: "HTTP", target: "external-api.example.com", data: "https://external-api.example.com/data?id=123", duration: 250, resultCode: "200", success: true, properties: { apiVersion: "v1" } }); client.trackDependency({ name: "SELECT users", dependencyTypeName: "SQL", target: "sql-server.database.windows.net", data: "SELECT * FROM users WHERE status = 'active'", duration: 45, resultCode: "0", success: true, properties: { database: "UserDB" } }); client.trackDependency({ name: "GET user:123", dependencyTypeName: "Redis", target: "redis-cache.redis.cache.windows.net", data: "GET user:123", duration: 5, resultCode: "0", success: true }); client.trackDependency({ name: "POST /payment-gateway", dependencyTypeName: "HTTP", target: "payments.stripe.com", data: "https://payments.stripe.com/v1/charges", duration: 30000, resultCode: "504", success: false, properties: { errorMessage: "Gateway timeout" } }); ``` ``` -------------------------------- ### Flush Telemetry and Shutdown Application Insights Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Properly flush all pending telemetry data and shut down the Application Insights client for a graceful application termination. Register handlers for `SIGTERM` and `SIGINT` to ensure cleanup. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Track some telemetry client.trackEvent({ name: "ApplicationStarted" }); // Flush immediately (async) await client.flush(); console.log("Telemetry flushed"); // Graceful shutdown handler async function gracefulShutdown() { console.log("Shutting down..."); // Track shutdown event client.trackEvent({ name: "ApplicationShutdown", properties: { reason: "SIGTERM" } }); // Flush all pending telemetry await client.flush(); // Shutdown the client await client.shutdown(); console.log("Application Insights shutdown complete"); process.exit(0); } // Register shutdown handlers process.on("SIGTERM", gracefulShutdown); process.on("SIGINT", gracefulShutdown); // Alternative: Use dispose for complete cleanup process.on("beforeExit", () => { appInsights.dispose(); }); ``` -------------------------------- ### Track HTTP Requests Manually with Application Insights Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Use `trackRequest` to manually log HTTP requests when automatic collection is insufficient. Capture details like name, URL, duration, result code, success status, and custom properties. Useful for custom API endpoints or non-standard request handling. ```javascript const appInsights = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Track a successful request client.trackRequest({ name: "GET /api/users", url: "https://api.example.com/api/users?page=1", duration: 150, resultCode: "200", success: true, properties: { userId: "admin-123", apiVersion: "v2" }, measurements: { responseSize: 4096, recordCount: 50 } }); ``` ```javascript // Track a failed request client.trackRequest({ name: "POST /api/orders", url: "https://api.example.com/api/orders", duration: 5000, resultCode: "500", success: false, properties: { orderId: "ORD-789", errorType: "InternalServerError", errorMessage: "Database connection timeout" } }); ``` ```javascript // Track request with custom ID for correlation client.trackRequest({ id: "custom-request-id-12345", name: "PUT /api/inventory", url: "https://api.example.com/api/inventory/SKU-123", duration: 200, resultCode: "204", success: true, time: new Date() // When the request started }); ``` -------------------------------- ### trackRequest - HTTP Request Tracking API Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Manually track HTTP requests when automatic instrumentation doesn't capture them or for custom request scenarios. ```APIDOC ## trackRequest - HTTP Request Tracking ### Description Manually track HTTP requests when automatic instrumentation doesn't capture them or for custom request scenarios. ### Method `client.trackRequest(requestData)` ### Parameters #### Request Body - **name** (string) - Required - The name of the request (e.g., 'GET /api/users'). - **url** (string) - Required - The URL of the request. - **duration** (number) - Required - The duration of the request in milliseconds. - **resultCode** (string) - Required - The result code of the request (e.g., '200', '500'). - **success** (boolean) - Required - Indicates if the request was successful. - **id** (string) - Optional - A unique identifier for the request, useful for correlation. - **time** (Date) - Optional - The timestamp when the request started. - **properties** (object) - Optional - Custom properties for filtering and segmentation. - **measurements** (object) - Optional - Custom measurements associated with the request. ### Request Example ```javascript client.trackRequest({ name: "GET /api/users", url: "https://api.example.com/api/users?page=1", duration: 150, resultCode: "200", success: true, properties: { userId: "admin-123", apiVersion: "v2" }, measurements: { responseSize: 4096, recordCount: 50 } }); client.trackRequest({ name: "POST /api/orders", url: "https://api.example.com/api/orders", duration: 5000, resultCode: "500", success: false, properties: { orderId: "ORD-789", errorType: "InternalServerError" } }); ``` ``` -------------------------------- ### Log Diagnostic Trace Messages Source: https://context7.com/microsoft/applicationinsights-node.js/llms.txt Use trackTrace to log diagnostic messages, such as informational, warning, verbose, or error traces. These messages help in monitoring application flow and debugging. ```javascript const appInsights = require("applicationinsights"); const { KnownSeverityLevel } = require("applicationinsights"); appInsights.setup("YOUR_CONNECTION_STRING").start(); const client = appInsights.defaultClient; // Log informational trace client.trackTrace({ message: "User authentication successful", severity: KnownSeverityLevel.Information, properties: { userId: "user-123", authMethod: "OAuth2" } }); // Log warning trace client.trackTrace({ message: "Cache miss for frequently accessed data", severity: KnownSeverityLevel.Warning, properties: { cacheKey: "user-preferences-123", fallbackSource: "database" } }); // Log verbose trace for debugging client.trackTrace({ message: "Processing batch item", severity: KnownSeverityLevel.Verbose, properties: { batchId: "batch-456", itemIndex: "42", processingStep: "validation" }, measurements: { processingTimeMs: 15.5 } }); // Log error trace client.trackTrace({ message: "Failed to send notification email", severity: KnownSeverityLevel.Error, properties: { recipientEmail: "user@example.com", templateId: "welcome-email", smtpError: "Connection timeout" } }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.