Application Insights

The Azure SDK for JavaScript provides robust tools to integrate Application Insights into your Node.js and browser applications. Application Insights is a powerful application performance management (APM) service that helps you understand how your live applications are performing and diagnose issues with minimal disruption.

Key Features

  • Automatic collection of requests, dependencies, exceptions, and traces.
  • Custom event and metric tracking.
  • Performance analysis and anomaly detection.
  • End-to-end transaction tracing.
  • Real-time monitoring and alerting.

Getting Started

To start using Application Insights with the JavaScript SDK, you'll need to:

  1. Create an Application Insights Resource: In the Azure portal, create an Application Insights resource to get your instrumentationKey.
  2. Install the SDK: Use npm or yarn to add the SDK to your project.

Installation

npm install @azure/applicationinsights-sdk

Or

yarn add @azure/applicationinsights-sdk

Usage in Node.js

Initialize the SDK with your instrumentation key and start tracking.

Example: Node.js Initialization


const appInsights = require("@azure/applicationinsights-sdk");

// Replace with your actual instrumentation key
const instrumentationKey = "YOUR_INSTRUMENTATION_KEY"; 

appInsights.setup(instrumentationKey).start();

console.log("Application Insights initialized and started.");

// Example of tracking a custom event
appInsights.defaultClient.trackEvent({ name: "MyApp.SessionStart" });

// Example of tracking an exception
try {
    throw new Error("Something went wrong!");
} catch (error) {
    appInsights.defaultClient.trackException({ exception: error });
}

// Example of tracking a metric
appInsights.defaultClient.trackMetric({ name: "UsersLoggedIn", value: 10 });
                    

Usage in Browser

For browser applications, you can use the Application Insights JavaScript SDK.

Example: Browser Initialization


// Import or include the SDK script
// e.g., 

// Initialize with your instrumentation key
window.appInsights.setup("YOUR_INSTRUMENTATION_KEY").start();

console.log("Application Insights initialized for browser.");

// Track a page view
window.appInsights.trackPageView({ name: document.title });

// Track a custom event
window.appInsights.trackEvent({ name: "AddToCart", properties: { item: "Widget", price: 10.99 } });
                    

Further Resources