ApplicationInsights-JS

trackPageView

applicationInsights.trackPageView(pageView: IPageViewTelemetry)

The IPageViewTelemetry interface is below:

Parameter Type Description
name? string Optional
Name of the pageview. Defaults to the document title.
uri? string Optional
A relative or absolute URL that identifies the page or other item. Defaults to the window location.
refUri? string Optional
The URL of the previous page that sent the user to the current page.
pageType? string Optional
Page Type string. Describes how you classify this page, e.g. errorPage, formPage, etc.
isLoggedIn? boolean Optional
Whether or not the user is logged in
properties? dictionary Optional
Map of string to any: Additional data used to filter pages in the portal. Defaults to empty.

Note: To send a custom duration (ms) of your pageview as an argument, it must be included in the properties named field. E.g appInsights.trackPageView({ properties: { duration: 123.45 } });.

startTrackPage

startTrackPage(name?: string)

Starts the timer for tracking a page load time. Use this instead of trackPageView if you want to control when the page view timer starts and stops, but don’t want to calculate the duration yourself. This method doesn’t send any telemetry. Call stopTrackPage to log the end of the page view and send the event.

Parameter Type Description
name? string Optional
The name used to identify the page in the portal. Defaults to the document title.

stopTrackPage

stopTrackPage(name?: string, url?: string);

Stops the timer that was started by calling startTrackPage and sends the pageview load time telemetry with the specified properties and measurements. The duration of the page view will be the time between calling startTrackPage and stopTrackPage.

Parameter Type Description
name? string Optional
The name used to identify the page in the portal. Defaults to the document title.
url? string Optional
A relative or absolute URL that identifies the page or similar item. Defaults to the window location.

trackMetric

trackMetric(metric: IMetricTelemetry)

Log a positive numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.

To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the telemetry bandwidth by aggregating multiple measurements and sending the resulting average and sampleCount at intervals.

IMetricTelemetry is described below

Parameter Type Description
name string Required
A string that identifies the metric. In the portal, you can select metrics for display by name.
average number Required
Either a single measurement, or the average of several measurements. Should be >=0 to be correctly displayed.
sampleCount? number Optional
Count of measurements represented by the average. Defaults to 1. Should be >=1.
min? number Optional
The smallest measurement in the sample. Defaults to the average. Should be >= 0.
max? number Optional
The largest measurement in the sample. Defaults to the average. Should be >= 0.
properties? dictionary Optional
Map of string to any: Additional data used to filter pages in the portal. Defaults to empty.

trackException

trackException(exception: IExceptionTelemetry)

Log an exception you have caught. Exceptions caught by the browser are also automatically logged.

IExceptionTelemetry is described below

Parameter Type Description
exception Error Required
Error object
severityLevel? SeverityLevel (number) Optional
Severity of the message, ranging from verbose to critical
properties? dictionary Optional
Map of string to any: Additional data used to filter pages in the portal. Defaults to empty.

By default, uncaught browser exceptions are caught by the SDK and reported to the portal. To disable this behavior, insert the following line in the config section below your connection string:

{
  connectionString: "your connection string",
  disableExceptionTracking: true
}

trackTrace

trackTrace(trace: ITraceTelemetry)

Log a diagnostic event such as entering or leaving a method.

The ITraceTelemetry interface is described below

Parameter Type Description
message string Required
Diagnostic data. Can be much longer than an event’s name.
severityLevel? SeverityLevel (number) Optional
Severity of the message, ranging from verbose to critical
properties? dictionary Optional
Map of string to any: Additional data used to filter pages in the portal. Defaults to empty.

In the portal, you can search on message content and display individual trackTrace events. (Unlike trackEvent, you can’t filter on the message content in the portal.)

trackDependencyData

trackDependencyData(dependency: IDependencyTelemetry)

Log a dependency call (for instance: ajax)

The IDependencyTelemetry interface is described below

Parameter Type Description
id string Required
Unique id, this is used by the backend to correlate server requests.
responseCode number Required
Response code returned by the dependency request (e.g., 200 for a success).
name? string Optional
Name of the command initiated with this dependency call.
duration? number Optional
Elapsed time of request & reply
success? boolean Optional
Whether or not the request was successful or not (e.g., responseCode in the range 200-299)
startTime? Date Optional
Dependency start timestamp.
correlationContext? string Optional
correlation context from the server.
type? string Optional
Dependency type name.
data? string Internal
Command initiated by this dependency call. This is not a user settable field. data is automatically set based on the dependency name (if available). Please include additional custom properties as part of the properties value below.
target? string Optional
Target site of a dependency call.
properties? dictionary Optional
Map of string to any: Additional data used to filter pages in the portal. Defaults to empty.

trackEvent

applicationInsights.trackEvent(event: IEventTelemetry)

The IEventTelemetry interface is below:

Parameter Type Description
name string Required
An event name string.
properties? dictionary Optional
Map of string to any: Additional data used to filter pages in the portal. Defaults to empty.
measurements? dictionary Optional
Map of string to any: Additional data (metrics) used to filter pages in the portal. Defaults to empty.

flush

flush(isAsync?: boolean, callBack?: () => void): void | IPromise<void>

Immediately send all queued telemetry. By default, it is sent asynchronously.

Note: You don’t have to use flush, as it is automatically called at an interval and when the user closes the window.

setAuthenticatedUserContext

setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie = false)
Set the authenticated user id and the account id. Use this when you have identified a specific signed-in user. Parameters must not contain spaces or ,;=

The method will only set the authenticatedUserId and accountId for all events in the current page view. To set them for all events within the whole session, you should either call this method on every page view or set storeInCookie = true.

Parameter Type Description
authenticatedUserId string Required
An id that uniquely identifies a user of your app. No spaces, comma, semicolon, equals or vertical bar.
accountId? string Optional
An optional account id, if your app groups users into accounts. No spaces, comma, semicolon, equals or vertical bar.

In the portal, this will add to the count of authenticated users. Authenticated users provide a more reliable count of the number of real users than the count of anonymous users.

The authenticated user id will be available as part of the context of the telemetry sent to the portal, so that you can filter and search on it. It will also be saved as a cookie and sent to the server, where the server SDK (if installed) will attach it to server telemetry.

clearAuthenticatedUserContext

clearAuthenticatedUserContext ()

Clears the authenticated user id and the account id from the user context, and clears the associated cookie.

addTelemetryInitializer

public addTelemetryInitializer(telemetryInitializer: (item: ITelemetryItem) => boolean | void)

Adds a telemetry initializer to the collection. Telemetry initializers will be called one by one with the telemetryItem of type ITelemetryItem, in the order they were added, before the telemetry item is pushed for sending. If one of the telemetry initializers returns false or throws an error, then the telemetry item will not be sent.

addDependencyListener

public addDependencyListener(dependencyListener: (dependencyDetails: IDependencyListenerDetails) => void): IDependencyListenerHandler;

// Example Usage
let handler = appInsights.addDependencyListener((details) => {
    // You have complete access to the xhr instance
    // details.xhr: XMLHttpRequest;

    // Or if a fetch request you have complete access to the input and init objects
    // details.input: Request | string;
    // details.init: RequestInit;

    // Access or change the W3C traceId that will be added to the outbound request
    details.traceId = "";

    // Access or change the W3C spanId that will be added to the outbound request
    details.spanId = "";

    // Access or change the W3C traceflags that will be added to the outbound request
    details.traceFlags = 1;

    // Add additional context values (any) that can be used by other listeners and is
    // also passed to any dependency initializers
    details.context.someValue = 1234;
});

// [Optional] Remove the dependency initializer
handler.remove();

A dependency listener is a callback function that allows you to perform additional manipulation of the request details before the request is performed.

This includes :-

addDependencyInitializer

public addDependencyInitializer(dependencyInitializer: (item: IDependencyInitializerDetails) => boolean | void): IDependencyInitializerHandler

// Example Usage
let handler = appInsights.addDependencyInitializer((details) => {
    details.item.xxxx = "";   // item is the telemetry event "before" it's been processed

    // [Optional] To stop any event from being reported you can
    // return false;
});


// [Optional] Remove the dependency initializer
handler.remove();

A Dependency Initializer is very similar to a Telemetry Initializer in that it allows you modify the contents of collected telemetry before being sent from the user’s browser. And you can also returning false to cause the event to not be emitted.

The differences between a telemetry initializer and a dependency initializer are :-

The input argument to addDependencyInitializer is a callback that takes a IDependencyInitializerDetails as an argument and returns a boolean or void. If returning false, the dependency event is not sent, else it proceeds to the next dependency initializer, if any, or is sent to processing pipeline to be sent to the telemetry collection endpoint.

getSender

applicationInsights.getSender() => Sender

Get the sender to configure and set the custom headers when using a custom endpoint.

addHeader

public addHeader(name: string, value: string)

Add header to request.

Custom extension

A custom plugin can be loaded by the SDK through config.extensions. All plugins must implement ITelemetryPlugin interface. These provide the capability of inspecting and updating data as it leaves the system, but also provides additional functionality to for one time initialization of extension state and pass in custom configuration through SKU configuration etc.

ITelemetryContext

context.application

application: IApplication

Details of the app you’re monitoring. See IApplication.

Property Type Description
application.ver string Application version
application.build string Application build

context.device

device: IDevice

The device the app is running on. See IDevice.

Property Type Description
device.id string Unique ID
device.deviceClass string Device class
device.model string Device model
device.resolution string Screen resolution
device.ip string IP address

context.user

user: IUserContext

Data about the current user. Users are identified by cookie, so one person can look like more than one user if they use different machines or browsers, or delete cookies. See IUserContext.

Property Type Description
user.id string Unique, cookie-based user id, automatically assigned.
user.authenticatedId string Id set by your app using setAuthenticatedUserContext when the user signs in.
user.accountId string Set by your app when the user signs in, if your app groups users into accounts.
user.accountAcquisitionDate string Account acquisition date

context.session

session: ISession

The user session. A session represents a series of user actions. A session starts with a user action. It ends at the last user activity when there is no more activity for sessionRenewalMs, or if it lasts longer than sessionExpirationMs. See ISession.

Property Type Description
session.id string Automatically assigned id
session.acquisitionDate number The dateTime when this session was created.
session.renewalDate number DateTime when telemetry was last sent with this session.

context.location

location: ILocation

Data from which the geographical location of the user’s device can be guessed. See ILocation.

Property Type Description
location.ip string IP address

context.telemetryTrace

Deprecated: Use appInsights.getTraceCtx() instead to get/set the current trace context. This returns an IDistributedTraceContext which supports distributed tracing and allows the core to manage the trace context.

telemetryTrace: ITelemetryTrace

Represents the distributed trace context. See ITelemetryTrace.

Property Type Description
telemetryTrace.traceID string Trace ID
telemetryTrace.parentID string Parent ID
telemetryTrace.traceFlags number W3C trace flags
telemetryTrace.name string Operation name

Use getTraceCtx() to access the current IDistributedTraceContext. This is the recommended replacement for the deprecated telemetryTrace.

// Get the current trace context - using the standard SKU (AISKU)
let traceCtx = appInsights.getTraceCtx();

// Or when using the core directly
// let traceCtx = appInsights.core.getTraceCtx();

// Read trace values
let traceId = traceCtx.traceId;
let spanId = traceCtx.spanId;
let traceFlags = traceCtx.traceFlags;
let pageName = traceCtx.pageName;

// Update trace values (updates current context only)
traceCtx.traceId = "new-trace-id";
traceCtx.spanId = "new-span-id";
traceCtx.traceFlags = 1;
traceCtx.pageName = "my-page";

// Replace the entire trace context
appInsights.core.setTraceCtx(newTraceCtx);
Property Type Description
traceId string 32 lowercase hex character trace ID, shared across all spans in a trace
spanId string 16 lowercase hex character span ID, unique identifier for this span
traceFlags number W3C trace flags (8-bit bitmap), bit 0x01 indicates sampling
pageName string Current page name
traceState IW3cTraceState Vendor-specific trace state for cross-system correlation
parentCtx IDistributedTraceContext Parent context (read-only)
isRemote boolean Whether context was propagated from a remote parent