Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Track web service events and metrics

Visual Studio 2013

Application Insights is in preview.

When you have set up Application Insights for your web application, you get basic information about the number of users visit your application and the browsers types they use, in addition to performance information. You can add more detailed usage information by tracking events and metrics.

The services SDK has a very low overhead and is easy to use. You insert code into your server application to track events and transactions. After you deploy the instrumented service, the Microsoft Application Insights service collects the data, analyzes it, and presents the results in the form of graphs and logs.

Caution note Caution

This is about the older version of Application Insights in Visual Studio Online. There’s a new version in Microsoft Azure. The new version has a significantly different API.

How do I know which I’m using, and how do I choose?

Suppose your web application helps users to buy and sell stocks and shares. You'd like to see charts of how often items are bought and sold.

Insert this call into your code where the transaction to buy stocks begins:

ServerAnalytics.CurrentRequest.LogEvent(
     // Event path name, for example "server1/open/buy": 
     "server1/" + order.Status + "/" + order.orderType); 

If you use "/" to separate the event name into elements, the report organizes the events into a hierarchy. Don’t use '/' as the first character. Anything after ‘?’ or ‘#’ will be ignored.

If you log events from another component of the same application, for example in a web page or Windows Store app, or a separate server, make sure that the events have distinct paths. They will all appear in the same report.

Log as many events as you like. For example, you might log an event when a new user registers; or you could find out how many users start a transaction and compare it with the number of users that complete it.

Deploy your application. As your events are logged, you’ll see event counts appearing under USAGE / Features.

Open USAGE, Features, Events and select your app

You can log additional properties along with an event. The properties can be used to filter the results—for example, to see sales of one particular stock.

// (Optional) Properties associated with the event: 
var properties = new Dictionary<string,object>(){
         // Any number of string properties:
         {"Exchange", "New York"},
         {"Stock", order.stockSymbol}};

ServerAnalytics.CurrentRequest.LogEvent(
     // Event path name, for example "open/buy": 
     order.Status + "/" + order.orderType, properties);      

In the dictionary, you can include any number of properties. They should be of string type, or a non-numeric type that can be converted to strings.

Security noteSecurity Note

Take care not to log personally identifiable information in the properties.

When you run your application, the properties appear in the filter menu when you select a specific leaf event.

To see the filters, expand the parent event group, and select a particular event in the table – in this example, we expanded ‘open’ and selected ‘buy’:

Expand event groups to get to the leaf event

You can send a numeric property (integer or floating-point) with an event: for example, the price of a sale. In the report chart, you’ll see average, minimum and maximum values when you hover over any event point.

Add the numeric value to the properties dictionary. You must add only one numeric property for each event.

double price = ...;
// (Optional) Properties associated with the event: 
var properties = new Dictionary<string,object>(){
         // One numeric property:
         {"Price", price},
         // Any number of string properties:
         {"Exchange", "New York"},
         {"Stock", order.stockSymbol}};

ServerAnalytics.CurrentRequest.LogEvent(
     // Event path name, for example "open/buy": 
     order.Status + "/" + order.orderType, properties);      

Use timed events to measure durations. For example, you could find out how long is the average interval between opening a trade and closing it. Create a timed event when the task starts. The event will be sent to Application Insights when you call End() or dispose the timed event.

// On opening the trade: 
var timedEvent = ServerAnalytics.CurrentRequest 
            .StartTimedEvent ("trade/buy"); 
... 
if (tradeIsCanceled)
{
  timedEvent.Cancel();
}
// On completing the trade: 
timedEvent.End();

You can also complete the event by disposing it:

using (var timedEvent = ServerAnalytics.CurrentRequest.StartTimedEvent("TradeService/SendOrder"))
{
  ...// Perform an operation you want to time.
  if (operationWasCanceled)
  {
     timedEvent.Cancel();
  }
  // Event is automatically completed on disposal, 
  // unless Cancel() was called.
} // end using

If you call Cancel(), no log of the event is sent, even if you subsequently call End().

Run your app in debug mode and test it. You’ll see your events almost immediately in the streaming data page of Application Insights. After about 5-15 minutes, data will start to appear in the USAGE pages.

When you build your app in production mode and redeploy it, you’ll see aggregated data gradually building up in USAGE.

Choose DETAILS to see more information about logged events:

In the chart hearder, choose Details

The durations of timed events are shown in milliseconds.

To focus on a particular time span, use the zoom buttons or set the span in the small overview graph at the bottom of the page. You can set its date range near the top of the page.

A number of terms are used in the graphs. Here’s what they mean:

Sessions

A session begins when a user interacts with an application and terminates after a period of inactivity longer than 30 minutes.

The event reports show the number of sessions in which that event occurs.

Activities

The count of events and page views that are logged. The activities report summarizes all of these types together, but you can go to the events and page views reports to filter the events by type.

Unique Users

The number of users who engage in one or more sessions from a particular client machine. This count uses a cookie to store a user ID. If the same user works on a different machine or cleans up cookies, they will be counted twice.

Active Users

The number of separate users that interact with the web site in a day.

New and returning users

New sessions counts the number of users that appear to have never used the web site before. A user will be counted as new if they clean up cookies or visit the site from a different client machine.

Returning sessions indicates the number of sessions from users who have used the site before from the same client machine.

Authenticated users

This count shows results only if you set the AppUserId value in your code, which you can use if you implement a method for users to login to your site. It gives a more accurate count of individual users because it doesn’t depend on cookies.

Usually you set these properties in ApplicationInsights.config, in the root folder of your app project. The properties are defined inside the <ServerAnalytics> node. In the default config file, there are two copies of ServerAnalytics: one in each of the Development and Production profiles.

You can also read and set some of these properties at runtime. Use the namespace Microsoft.ApplicationInsights.Telemetry.Services.

ServerAnalytics.Enabled

To prevent data being collected and sent to Application Insights:

<ServerAnalytics enabled="false">...</ServerAnalytics>
ServerAnalytics.Enabled = false;
SendToRawStream

Send data to the Raw Event tile and Diagnostics/Streaming page. In the default config file, this is true in the Development profile and false in the Production profile.

<SendToRawStream>true</SendToRawStream>
CollectUserName

Send the current user name with the raw stream events, so that you can distinguish events sent by different members of the development team. This is most useful when you are debugging the app in your own machine. In the default config file, this is true in the Development profile.

<CollectUserName>true</CollectUserName>
CollectMachineName

Send the machine name with events to report in the raw stream data, so that you can distinguish events sent by different members of the development team. This is most useful when you are debugging the app in your own machine. In the default config file, this is true in the Development profile.

<CollectMachineName>true</CollectMachineName>
ServerAnalytics.DataUploadIntervalInSeconds

By default the SDK sends data to the Application Insights service every one minute. You can set it between 1 and 30 minutes. If more than 1000 events are collected, the data will be sent anyway.

<DataUploadIntervalInSeconds>60</DataUploadIntervalInSeconds>
ServerAnalytics.DataUploadIntervalInSeconds = 60;
ServerAnalytics.AutoFillClientPropertiesFromRequest

Set this to false if you don't want the SDK to collect properties automatically from the client requests, including the client's IP address.

ServerAnalytics.CollectClientIPAddress

Set this false if you don't want to collect the client's IP address, but you do want to collect other client properties. The client IP address is collected only if it is available in the HTTP request. You can set ServerAnalytics.CurrentRequest.ClientIPAddress yourself.

ServerAnalytics.ApplicationInsightsId

(Read-only.) Returns the component ID.

The user properties are specific to users. Set user properties separately for each request. They can be set anywhere in the code and should be set before logging events or timed events.

AnonymousId

Used by the Application Insights service to track users consistently and to build reports such as unique visitors, new and returning visitors, visitor recency, visitor loyalty and session duration. You can set it to a GUID that is associated with the user to consistently track their usage. If not set then the SDK defaults it to a GUID based on the server.  

ServerAnalytics.CurrentRequest.AnonymousId = "a guid"

If there is no GUID stored for the user then you can use the following function to calculate a GUID based on user id:

private static Guid AppUserIdToAnonymousId(string src)
{
  byte [] stringbytes = Encoding.UTF8.GetBytes(src);
  byte [] hashedBytes = new System.Security.Cryptography
                .SHA1CryptoServiceProvider()
                .ComputeHash(stringbytes);
  Array.Resize(ref hashedBytes, 16);
  return new Guid(hashedBytes);
}
SessionId

Used to track a user’s session. The SDK automatically sets it to the AnonymousId. You should set this only in cases where each session needs to be separately tracked. In the App Analytics service, a session ends when no event is received for 30 minutes.

AccountId

Set this if you know the account id of a user, such as Contoso.

AppUserId

Set this if you know the id of a user, such as mike@contoso.com. This property is the basis for the Authenticated Users report.

By default, this data is collected from the HTTP request, if it is available and if CollectClientIpAddress is true. You can set the request properties if you want values to appear in the Application Insights reports. If you want to set these properties, do so before logging events. The best place to set them is in the Application_BeginRequest() method in global.asax.

The data is not collected in worker roles and in some other situations such as private networks.

ClientIPAddress

IP address of the client browser.

ServerAnalytics.CurrentRequest.ClientIPAddress = 
    HttpContext.Current.Request.ServerVariables.Get("REMOTE_ADDR");
ClientLanguage

The language of the client’s platform. It appears in the Languages report in Application Insights.

ServerAnalytics.CurrentRequest.ClientLanguage = 
    HttpContext.Current.Request.ServerVariables.Get("HTTP_ACCEPT_LANGUAGE");
ClientBrowser

The browser used by the application’s client. It appears in the Browsers report in Application Insights. It is recommended but not required to send the browser information in a two level hierarchy such as "Internet Explorer/Internet Explorer 10.0" for better visualization in the reports.

ServerAnalytics.CurrentRequest.ClientBrowser = 
    HttpContext.Current.Request.Browser.Type.ToString();
ClientOperatingSystem

The client’s operating system. It appears in the Operating Systems report in Application Insights.

ServerAnalytics.CurrentRequest.ClientOperatingSystem = 
    HttpContext.Current.Request.Browser.Platform.ToString();#

If you’re using Visual Studio 2012, add the Application Insights Telemetry SDK to your web project.

  1. Log in to Visual Studio Online and go to Application Insights.

  2. If you want the results to appear under a new component name:

    1. Choose Add Application.

    2. Choose ‘click here’ to avoid setting up a performance monitor.

      Answer the questions: (server component) No, (type of application) Web Site. Continue to the instructions page.

    3. Under step “Name your application”, provide a name and choose Create.

    4. Ignore the other steps.

  3. Open the USAGE page.

  4. Select the application component under which you want the results to appear.

    A configuration page appears.

  5. Choose Web Service, and then continue to the instructions page.

  6. Follow the instructions to install Application Insights Telemetry SDK on your project.

  7. Run your app (F5) and use it to generate some data.

  8. In Application Insights, after 5-15 minutes, data will appear on the USAGE pages.

Deploy your app and view the results, or insert code to log events.

This usually happens automatically when you upload your web application project. The performance monitoring agent reads the DisplayName from the ApplicationInsights.config file in the root directory of the web application. You might have to restart the Microsoft Monitoring Agent.

Alternatively, you can change the component ID in ApplicationInsights.config to direct the usage data to the application component of your choice. To get the component ID, go to the USAGE page in Application Insights and select the application component. You should see a configuration page because you haven’t yet configured usage monitoring for this component. Choose Web service, and on the next page, copy the component guid from code snippet in step 3. Ignore the other steps. In Visual Studio, in your web app project, replace the component ID in ApplicationInsights.config.

In Application Insights, application components are simply a way of grouping together metrics from different sources. For example, if you have already started monitoring the performance or availability of your web service, you will probably want to use the same application name when you install the SDK, so that you can easily correlate results from the different sources. But you can alternatively provide a new application name, in order to have the results appear separately.

The impact on request time and CPU is typically no more than a few percent. About 50MB of memory is used constantly by the SDK.

  • Creates an application component in Application Insights, in your Visual Studio Online account.

  • Adds project references to Microsoft.ApplicationInsights.Telemetry.Services and Microsoft.ApplicationInsights.Telemetry.Web.

  • Adds ApplicationInsights.config to your project, inserting the componentId of your application component, so that the data sent from your application will appear under your component.

  • Opens a browser on an Application Insights dashboard for your application component.

No. Performance monitoring and usage monitoring are independent features of Application Insights.

Of course, you get a fuller picture of what’s happening to your application if you use both services together. But you can set them up in any order.

Authenticated Users shows the number of distinct values of ServerAnalytics.CurrentRequest.AppUserId that have been set each day. Typically you set it to the id of the user when the user logs into your app.

Active Accounts shows the number of distinct values of ServerAnalytics.CurrentRequest.AccountId that have been set each day. Use it if your users belong to different groups or categories. For example, your application might serve a number of different organizations. When a user logs in, set AppUserId and AccountId.

Confirmation when you open Application Insights

Visual Studio passes your credentials to your default browser, which uses them to log in to the Application Insights site. We just want to check you’re OK with that, and give you the opportunity to use a different account. By default, the account is the same one you used when you created the project or added Application Insights to it. Nearly always, you just click through this dialog. But if you choose to use a different user account, it should be a member of the same corporate account, so that you can see your data.

  1. Watch the Raw event stream tile on the dashboard, or the Diagnostics, Streaming page. Data should appear there within a few seconds. The Usage pages show aggregated data about 15 minutes later.

  2. Check you’re configured for streaming.

    1. In Visual Studio, on the Build menu, open Configuration Manager. Check that the Active Build Configuration is Debug.

    2. Open ApplicationInsights.config in the root folder of your app project and check the following elements:

    3. This element determines which profile that is active when you build in Debug mode:

      <DebugBuildProfile>Development</DebugBuildProfile>

    4. Inside <Profile name="Development">, check that you see these elements:

      <ServerAnalytics enabled="true">
        <SendToRawStream>true</SendToRawStream>
        <CollectUserName>true</CollectUserName>
        <CollectMachineName>true</CollectMachineName>
        <DataUploadIntervalInSeconds>0.1</DataUploadIntervalInSeconds>
      </ServerAnalytics>
      
  3. Watch the debug output. The SDK logs messages to the Debug Output window in Visual Studio. You should see initialization messages, followed by messages when events are logged and sent.

    Debug output from server SDK running in F5

It stopped updating? Restart your app. If your app sends no data for 90 seconds, the refresh interval of the raw event view gradually increases to 30 minutes. It will speed up again after a refresh that sees new data, and will speed up immediately when you restart your app.

Old data vanished? The raw event stream has a limited buffer. When you’ve sent a lot of events, you won’t be able to scroll back to see the oldest ones in the raw event stream. But you will be able to see the aggregated events in the USAGE pages.

(If you want to log events for diagnostic purposes, see Search your diagnostic logs in Application Insights.)

You can have at most one numeric parameter in a TrackEvent call. The other parameters should be used to define string values that can be used to filter the events. If you have a numeric value that you want to use in this way, convert it to a string.

In ApplicationInsights.config in the root folder of your web service project, set <ComponentName> to be the name under which you see usage data. Upload the config file to your server.

When the performance data starts to appear under the correct application component name, you can delete the old performance data on the Overview, Applications page.

Add following to configurations section of web.config or to the app.config. Make sure that sufficient permissions for tracing are provided on the folder specified below. Other listeners can be also added. See DiagnosticMonitorTraceListener and System.Diagnostics.TraceListener.

<system.diagnostics>
<trace autoflush="true"></trace>
<sources>
<source name="Microsoft.ApplicationInsights.Telemetry.Services" switchValue="All">
<listeners>
<add name="DiagnosticMessageTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
traceOutputOptions="ProcessId, ThreadId, DateTime"
initializeData="location of the log file" />
</listeners>
</source>
</sources>
</system.diagnostics>
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft