Comprehensive type definitions for all telemetry data structures including events, traces, exceptions, metrics, requests, dependencies, and availability tests. These types define the structure and properties of telemetry data sent to Azure Monitor.
Common properties shared by all telemetry types.
/**
* Base telemetry interface encapsulating common properties
*/
interface Telemetry {
/** Telemetry timestamp (current time if not specified) */
time?: Date;
/** Additional data used to filter events and metrics in the portal */
properties?: { [key: string]: any };
}Track custom business events and user actions with associated measurements.
/**
* Telemetry about custom events of interest, such as application workflow events,
* business logic events (purchase) and anything you would like to track and aggregate by count
*/
interface EventTelemetry extends Telemetry {
/** Name of the event */
name: string;
/** Metrics associated with this event, displayed in Metrics Explorer */
measurements?: { [key: string]: number };
}Usage Examples:
const eventTelemetry: EventTelemetry = {
name: "ProductPurchased",
properties: {
productId: "laptop-001",
category: "electronics",
paymentMethod: "credit-card",
userId: "user123"
},
measurements: {
price: 999.99,
quantity: 1,
discountPercent: 10,
tax: 99.99
},
time: new Date()
};
client.trackEvent(eventTelemetry);Track trace messages and logging information with configurable severity levels.
/**
* Trace telemetry reports technical, usually detailed information about the environment,
* usage of resources, performance, capacity etc
*/
interface TraceTelemetry extends Telemetry {
/** Trace message */
message: string;
/** Trace severity level */
severity?: SeverityLevel;
/** Collection of custom measurements */
measurements?: { [propertyName: string]: number };
}
/**
* Severity levels for trace telemetry
*/
enum SeverityLevel {
Verbose = 0,
Information = 1,
Warning = 2,
Error = 3,
Critical = 4
}
/**
* Known severity levels that the service accepts (string-based)
*/
enum KnownSeverityLevel {
Verbose = "Verbose",
Information = "Information",
Warning = "Warning",
Error = "Error",
Critical = "Critical"
}Usage Examples:
const traceTelemetry: TraceTelemetry = {
message: "Database connection established successfully",
severity: SeverityLevel.Information,
properties: {
database: "user-db",
server: "db-server-01",
connectionPool: "primary"
},
measurements: {
connectionTimeMs: 150,
poolSize: 10
}
};
client.trackTrace(traceTelemetry);Track exceptions and errors with complete error information and context.
/**
* Exception telemetry for tracking application errors and exceptions
*/
interface ExceptionTelemetry extends Telemetry {
/** Exception object with stack trace */
exception: Error;
/** Severity level of the exception */
severity?: SeverityLevel;
/** Collection of custom measurements */
measurements?: { [propertyName: string]: number };
}Usage Examples:
try {
await riskyOperation();
} catch (error) {
const exceptionTelemetry: ExceptionTelemetry = {
exception: error,
severity: SeverityLevel.Error,
properties: {
operation: "riskyOperation",
userId: getCurrentUserId(),
context: "payment-processing",
version: "1.2.0"
},
measurements: {
operationDurationMs: Date.now() - startTime,
retryCount: 3
}
};
client.trackException(exceptionTelemetry);
}Track numeric values and performance indicators with aggregation support.
/**
* Metric telemetry for tracking numeric values and performance indicators
*/
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
const simpleMetric: MetricTelemetry = {
name: "QueueLength",
value: 47,
properties: {
queueName: "order-processing",
server: "worker-01"
}
};
client.trackMetric(simpleMetric);
// Aggregated metric with statistics
const aggregatedMetric: MetricTelemetry = {
name: "ResponseTime",
value: 156.7,
count: 100,
min: 45.2,
max: 1200.8,
stdDev: 89.3,
properties: {
endpoint: "/api/users",
method: "GET",
region: "us-west-2"
}
};
client.trackMetric(aggregatedMetric);Track HTTP requests and their performance characteristics.
/**
* Request telemetry for tracking HTTP requests and their performance
*/
interface RequestTelemetry extends Telemetry {
/** Request name or operation name (optional) */
name?: string;
/** Request URL (optional) */
url?: string;
/** Request duration in milliseconds */
duration: number;
/** Response code */
resultCode: string;
/** Success flag */
success: boolean;
/** Request ID (optional) */
id?: string;
/** Collection of custom measurements */
measurements?: { [propertyName: string]: number };
}Usage Examples:
const requestTelemetry: RequestTelemetry = {
name: "POST /api/orders",
url: "https://api.example.com/api/orders",
duration: 250,
resultCode: 201,
success: true,
properties: {
userId: "user123",
orderId: "order-456",
clientIP: "192.168.1.100"
},
measurements: {
requestSize: 1024,
responseSize: 512
}
};
client.trackRequest(requestTelemetry);Track calls to external dependencies like databases, web services, and APIs.
/**
* Dependency telemetry for tracking calls to external dependencies
*/
interface DependencyTelemetry extends Telemetry {
/** Dependency name */
name: string;
/** Command or query executed (optional) */
data?: string;
/** Call duration in milliseconds */
duration: number;
/** Success flag (optional) */
success?: boolean;
/** Dependency type (optional, e.g., "HTTP", "SQL", "Redis") */
dependencyTypeName?: string;
/** Target server or endpoint (optional) */
target?: string;
/** Result code (optional) */
resultCode?: string | number;
/** Dependency call ID (optional) */
id?: string;
/** Collection of custom measurements */
measurements?: { [propertyName: string]: number };
}Usage Examples:
// Database dependency
const dbDependency: DependencyTelemetry = {
name: "GetActiveUsers",
data: "SELECT * FROM users WHERE active = 1",
duration: 45,
success: true,
dependencyTypeName: "SQL",
target: "user-database.company.com",
resultCode: "0",
properties: {
database: "UserDB",
commandType: "SELECT"
},
measurements: {
rowCount: 150,
connectionPoolSize: 10
}
};
client.trackDependency(dbDependency);
// HTTP API dependency
const apiDependency: DependencyTelemetry = {
name: "GetUsersAPI",
data: "GET /users",
duration: 200,
success: true,
dependencyTypeName: "HTTP",
target: "api.example.com",
resultCode: 200,
properties: {
userAgent: "MyApp/1.0",
endpoint: "/users"
},
measurements: {
requestSize: 0,
responseSize: 2048
}
};
client.trackDependency(apiDependency);Track availability test results and synthetic monitoring data.
/**
* Availability telemetry for tracking synthetic monitoring and availability tests
*/
interface AvailabilityTelemetry extends Telemetry {
/** Identifier of a test run to correlate steps */
id: string;
/** Name of the test that these results represent */
name: string;
/** Request duration in milliseconds */
duration: number;
/** Success flag */
success: boolean;
/** Name of the location where the test was run from */
runLocation: string;
/** Diagnostic message for the result */
message: string;
/** Metrics associated with this event */
measurements?: { [key: string]: number };
}Usage Examples:
const availabilityTelemetry: AvailabilityTelemetry = {
id: "test-run-123",
name: "HomePage Availability Test",
duration: 1200,
success: true,
runLocation: "West US 2",
message: "Test completed successfully",
properties: {
testType: "synthetic",
browser: "chromium",
version: "1.0"
},
measurements: {
responseTime: 1200,
contentSize: 45600,
dnsLookupTime: 50
}
};
client.trackAvailability(availabilityTelemetry);Track page views and navigation in web applications.
/**
* Page view telemetry for tracking page navigation in web applications
*/
interface PageViewTelemetry extends Telemetry {
/** Page name */
name: string;
/** Page URL (optional) */
url?: string;
/** Page load duration in milliseconds (optional) */
duration?: number;
/** Referring URI (optional) */
referredUri?: string;
/** Page view ID (optional) */
id?: string;
}Usage Examples:
const pageViewTelemetry: PageViewTelemetry = {
name: "Product Details",
url: "https://store.example.com/products/laptop-001",
duration: 2500,
referredUri: "https://store.example.com/search?q=laptop",
properties: {
productId: "laptop-001",
category: "electronics",
userId: "user123"
},
measurements: {
loadTime: 2500,
imageCount: 6,
reviewCount: 24
}
};
client.trackPageView(pageViewTelemetry);Enumeration of all supported telemetry types for type checking and routing.
/**
* Enumeration of all telemetry types
*/
enum TelemetryType {
Event = "EventData",
Exception = "ExceptionData",
Trace = "MessageData",
Metric = "MetricData",
Request = "RequestData",
Dependency = "RemoteDependencyData",
Availability = "AvailabilityData",
PageView = "PageViewData"
}Legacy telemetry types for Node.js HTTP request and dependency tracking (deprecated in v3.x).
/**
* @deprecated Use RequestTelemetry instead
* Node.js HTTP request telemetry (legacy)
*/
interface NodeHttpRequestTelemetry extends Telemetry {
/** HTTP request object */
request: http.IncomingMessage;
/** HTTP response object */
response: http.ServerResponse;
/** Request duration */
duration: number;
/** Error object if request failed */
error?: any;
}
/**
* @deprecated Use DependencyTelemetry instead
* Node.js HTTP dependency telemetry (legacy)
*/
interface NodeHttpDependencyTelemetry extends Telemetry {
/** HTTP request options */
options: http.RequestOptions | https.RequestOptions | string;
/** HTTP request object */
request: http.ClientRequest;
/** Request duration */
duration: number;
/** Error object if request failed */
error?: any;
}import { TelemetryClient, SeverityLevel } from "applicationinsights";
const client = new TelemetryClient();
// Comprehensive telemetry tracking example
async function processOrder(orderData: any) {
const startTime = Date.now();
const operationId = `order-${Date.now()}`;
try {
// Track the start of order processing
client.trackEvent({
name: "OrderProcessingStarted",
properties: {
orderId: orderData.id,
customerId: orderData.customerId,
operationId: operationId
},
measurements: {
orderValue: orderData.total,
itemCount: orderData.items.length
}
});
// Track database call
const dbStart = Date.now();
const customer = await getCustomer(orderData.customerId);
client.trackDependency({
name: "GetCustomer",
data: `SELECT * FROM customers WHERE id = ${orderData.customerId}`,
duration: Date.now() - dbStart,
success: !!customer,
dependencyTypeName: "SQL",
target: "customer-db.company.com",
properties: { operationId }
});
// Track external API call
const apiStart = Date.now();
const paymentResult = await processPayment(orderData.payment);
client.trackDependency({
name: "ProcessPayment",
data: "POST /payments",
duration: Date.now() - apiStart,
success: paymentResult.success,
dependencyTypeName: "HTTP",
target: "payments.provider.com",
resultCode: paymentResult.statusCode,
properties: { operationId }
});
// Track successful completion
client.trackRequest({
name: "ProcessOrder",
url: "/api/orders",
duration: Date.now() - startTime,
resultCode: 200,
success: true,
properties: {
orderId: orderData.id,
operationId: operationId
}
});
// Track completion event
client.trackEvent({
name: "OrderProcessed",
properties: {
orderId: orderData.id,
operationId: operationId,
status: "completed"
},
measurements: {
processingTimeMs: Date.now() - startTime
}
});
} catch (error) {
// Track exception
client.trackException({
exception: error,
severity: SeverityLevel.Error,
properties: {
orderId: orderData.id,
operationId: operationId,
stage: "processing"
},
measurements: {
processingTimeMs: Date.now() - startTime
}
});
// Track failed request
client.trackRequest({
name: "ProcessOrder",
url: "/api/orders",
duration: Date.now() - startTime,
resultCode: 500,
success: false,
properties: {
orderId: orderData.id,
operationId: operationId,
errorMessage: error.message
}
});
throw error;
}
}