TelemetryClient provides comprehensive manual telemetry tracking capabilities for custom application monitoring. It enables direct submission of traces, events, exceptions, metrics, requests, dependencies, availability tests, and page views to Azure Monitor.
Main class for manual telemetry tracking with complete lifecycle management.
/**
* Application Insights telemetry client for manual tracking
*/
class TelemetryClient {
/** Context containing tags and session information */
context: Context;
/** Common properties added to all telemetry */
commonProperties: { [key: string]: string };
/** Client configuration */
config: Config;
/**
* Constructs a new TelemetryClient instance
* @param input - Connection string or instrumentation key (optional, reads from environment if not provided)
*/
constructor(input?: string);
/**
* Initialize the client (called automatically on first tracking call)
*/
initialize(): void;
/**
* Immediately send all queued telemetry
* @returns Promise that resolves when flush is complete
*/
flush(): Promise<void>;
/**
* Shutdown the client and clean up resources
* @returns Promise that resolves when shutdown is complete
*/
shutdown(): Promise<void>;
}Track trace messages and logging information with configurable severity levels.
/**
* Log a trace message
* @param telemetry - Trace telemetry data
*/
trackTrace(telemetry: TraceTelemetry): void;
interface TraceTelemetry extends Telemetry {
/** Trace message */
message: string;
/** Trace severity level */
severity?: SeverityLevel;
/** Collection of custom measurements */
measurements?: { [propertyName: string]: number };
}
enum SeverityLevel {
Verbose = 0,
Information = 1,
Warning = 2,
Error = 3,
Critical = 4
}Usage Examples:
import { TelemetryClient } from "applicationinsights";
const client = new TelemetryClient();
// Basic trace
client.trackTrace({
message: "User logged in successfully"
});
// Trace with severity and properties
client.trackTrace({
message: "Database connection failed",
severity: SeverityLevel.Error,
properties: {
database: "user-db",
connectionString: "[REDACTED]",
retryAttempt: "3"
},
measurements: {
responseTimeMs: 5000,
connectionPoolSize: 10
}
});Track custom business events and user actions with associated measurements.
/**
* Log a user action or other occurrence
* @param telemetry - Event telemetry data
*/
trackEvent(telemetry: EventTelemetry): void;
interface EventTelemetry extends Telemetry {
/** Name of the event */
name: string;
/** Metrics associated with this event */
measurements?: { [key: string]: number };
}Usage Examples:
// Business event tracking
client.trackEvent({
name: "ProductPurchased",
properties: {
productId: "laptop-001",
category: "electronics",
paymentMethod: "credit-card"
},
measurements: {
price: 999.99,
quantity: 1,
discountPercent: 10
}
});
// User interaction tracking
client.trackEvent({
name: "ButtonClicked",
properties: {
buttonId: "checkout-button",
page: "cart",
userId: "user123"
}
});Track exceptions and errors with full stack trace information.
/**
* Log an exception
* @param telemetry - Exception telemetry data
*/
trackException(telemetry: ExceptionTelemetry): void;
interface ExceptionTelemetry extends Telemetry {
/** Exception object */
exception: Error;
/** Severity level */
severity?: SeverityLevel;
/** Collection of custom measurements */
measurements?: { [propertyName: string]: number };
}Usage Examples:
try {
await riskyOperation();
} catch (error) {
client.trackException({
exception: error,
severity: SeverityLevel.Error,
properties: {
operation: "riskyOperation",
userId: getCurrentUserId(),
context: "payment-processing"
},
measurements: {
operationDurationMs: Date.now() - startTime
}
});
throw error; // Re-throw if needed
}Track numeric values and performance indicators with custom metrics.
/**
* Log a numeric value that is not associated with a specific event
* @param telemetry - Metric telemetry data
*/
trackMetric(telemetry: MetricPointTelemetry & MetricTelemetry): void;
interface MetricTelemetry extends Telemetry {
/** Metric name */
name: string;
/** Metric value */
value: number;
/** Sample count (optional) */
count?: number;
/** Minimum value (optional) */
min?: number;
/** Maximum value (optional) */
max?: number;
/** Standard deviation (optional) */
stdDev?: number;
}Usage Examples:
// Simple metric
client.trackMetric({
name: "QueueLength",
value: 47,
properties: {
queueName: "order-processing",
server: "worker-01"
}
});
// Aggregated metric
client.trackMetric({
name: "ResponseTime",
value: 156.7,
count: 100,
min: 45.2,
max: 1200.8,
stdDev: 89.3,
properties: {
endpoint: "/api/users",
method: "GET"
}
});Track HTTP requests and their performance characteristics.
/**
* Log a request (use only for requests not automatically captured)
* @param telemetry - Request telemetry data
*/
trackRequest(telemetry: RequestTelemetry): void;
interface RequestTelemetry extends Telemetry {
/** Request name */
name: string;
/** Request URL */
url: string;
/** Request duration in milliseconds */
duration: number;
/** Response code */
resultCode: string | number;
/** Success flag */
success: boolean;
/** Request ID (optional) */
id?: string;
}Usage Examples:
const startTime = Date.now();
try {
const result = await processRequest(requestData);
client.trackRequest({
name: "ProcessOrder",
url: "/api/orders",
duration: Date.now() - startTime,
resultCode: 200,
success: true,
properties: {
orderId: result.orderId,
customerId: requestData.customerId
}
});
} catch (error) {
client.trackRequest({
name: "ProcessOrder",
url: "/api/orders",
duration: Date.now() - startTime,
resultCode: 500,
success: false,
properties: {
errorMessage: error.message
}
});
}Track calls to external dependencies like databases, web services, and APIs.
/**
* Log a dependency call (use only for dependencies not automatically captured)
* @param telemetry - Dependency telemetry data
*/
trackDependency(telemetry: DependencyTelemetry): void;
interface DependencyTelemetry extends Telemetry {
/** Dependency name */
name: string;
/** Command/query executed */
data: string;
/** Call duration in milliseconds */
duration: number;
/** Success flag */
success: boolean;
/** Dependency type (e.g., "HTTP", "SQL", "Redis") */
dependencyTypeName: string;
/** Target server/endpoint (optional) */
target?: string;
/** Result code (optional) */
resultCode?: string | number;
/** Dependency call ID (optional) */
id?: string;
}Usage Examples:
// Database dependency
const dbStartTime = Date.now();
try {
const users = await db.query("SELECT * FROM users WHERE active = 1");
client.trackDependency({
name: "GetActiveUsers",
data: "SELECT * FROM users WHERE active = 1",
duration: Date.now() - dbStartTime,
success: true,
dependencyTypeName: "SQL",
target: "user-database.company.com",
resultCode: "0",
properties: {
database: "UserDB",
rowCount: users.length.toString()
}
});
} catch (error) {
client.trackDependency({
name: "GetActiveUsers",
data: "SELECT * FROM users WHERE active = 1",
duration: Date.now() - dbStartTime,
success: false,
dependencyTypeName: "SQL",
target: "user-database.company.com",
resultCode: error.code
});
}
// HTTP API dependency
const apiStartTime = Date.now();
const response = await fetch("https://api.example.com/users");
client.trackDependency({
name: "GetUsersAPI",
data: "GET /users",
duration: Date.now() - apiStartTime,
success: response.ok,
dependencyTypeName: "HTTP",
target: "api.example.com",
resultCode: response.status,
properties: {
userAgent: "MyApp/1.0"
}
});Track availability test results and synthetic monitoring.
/**
* Log information about availability of an application
* @param telemetry - Availability telemetry data
*/
trackAvailability(telemetry: AvailabilityTelemetry): void;
interface AvailabilityTelemetry extends Telemetry {
/** Identifier of a test run */
id: string;
/** Name of the test */
name: string;
/** Request duration in milliseconds */
duration: number;
/** Success flag */
success: boolean;
/** Name of the location where test was run */
runLocation: string;
/** Diagnostic message for the result */
message: string;
/** Metrics associated with this event */
measurements?: { [key: string]: number };
}Track page views and navigation in web applications.
/**
* Log a page view
* @param telemetry - Page view telemetry data
*/
trackPageView(telemetry: PageViewTelemetry): void;
interface PageViewTelemetry extends Telemetry {
/** Page name */
name: string;
/** Page URL (optional) */
url?: string;
/** Page load duration (optional) */
duration?: number;
/** Referring URI (optional) */
referredUri?: string;
/** Page view ID (optional) */
id?: string;
}Configure common properties and context information for all telemetry.
interface Context {
/** Context tags (role name, instance, etc.) */
tags: { [key: string]: string };
/** Session information */
sessionId?: string;
/** User information */
userId?: string;
}Usage Examples:
const client = new TelemetryClient();
// Set common properties for all telemetry
client.commonProperties = {
version: "1.2.0",
environment: "production",
region: "us-west-2"
};
// Configure context tags
client.context.tags["ai.cloud.roleName"] = "order-service";
client.context.tags["ai.cloud.roleInstance"] = "order-service-01";
client.context.tags["ai.application.ver"] = "1.2.0";