Blog

Sharepoint Online Performance Monitoring with Application Insights

By Mike Veazie
SharePoint, Performance, Application Insights

My site is slow! ... we've all heard it, but then after digging into the issue the site doesn't seem to have any issues.

This is where a tool like Application Insights comes in handy. Application Insights is an Application Performance Monitoring (APM) tool that is targeted at developers and IT pros. You can instrument server side and client side applications, and send performance and usage data back to Microsoft Azure. It is then available for ad-hoc queries, reports, automated alerts, and other ancillary monitoring features. Also, it's pretty cheap for basic use cases! You can check out the pricing here and for additional reading, check out Microsoft's documentation here.

Alright, let's get to the point. I'm going to show you how to do two neat things with Application Insights.
- First, how to collect telemetry on your SharePoint performance using the http response headers for x-sharepointhealthscore and spiislatency
- Second, how to collect custom metrics using Application Insights

Step 1, wiring up Application Insights

In the Azure portal, create an Application Insights instance. Then, at the bottom of your page, insert a <script/> block like this:

<script>
    var appInsights=window.appInsights||function(a){
        function b(a){c[a]=function(){var b=arguments;c.queue.push(function(){c[a].apply(c,b)})}}var c={config:a},d=document,e=window;setTimeout(function(){var b=d.createElement("script");b.src=a.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js",d.getElementsByTagName("script")[0].parentNode.appendChild(b)});try{c.cookie=d.cookie}catch(a){}c.queue=[];for(var f=["Event","Exception","Metric","PageView","Trace","Dependency"];f.length;)b("track"+f.pop());if(b("setAuthenticatedUserContext"),b("clearAuthenticatedUserContext"),b("startTrackEvent"),b("stopTrackEvent"),b("startTrackPage"),b("stopTrackPage"),b("flush"),!a.disableExceptionTracking){f="onerror",b("_"+f);var g=e[f];e[f]=function(a,b,d,e,h){var i=g&&g(a,b,d,e,h);return!0!==i&&c["_"+f](a,b,d,e,h),i}}return c
        }({
            instrumentationKey:"<guid-found-in-azure-portal>"
        });
    window.appInsights=appInsights;

    // More configuration will be added right here in next steps

</script>

Step 2, collecting SharePoint performance data

We'll be tracking the x-sharepointhealthscore and spiislatency response headers. A couple things to note here:
- First, this isn't perfect but it can give you some insight into your SharePoint tenant's performance. In order to get access to the Http response headers, we need to create a new Http request in JavaScript, and then pull the response headers from the call. Since we just need the response headers, we'll use a HEAD method to requests only for the headers. The problem with this is it's essentially a new SharePoint health score than the original page load.
- Second, since you are making a second request to the page, the SharePoint environment will receive more load than before. It should be minimal since we're just doing a HEAD request, but it could have unintended consequences.

Insert this code at the bottom of your <script/> block

var req = new XMLHttpRequest();
req.open('HEAD', document.location, false);
req.send(null); 

appInsights.trackPageView(
    _spPageContextInfo.webTitle,
    (window.location.protocol + "//" + window.location.hostname + _spPageContextInfo.serverRequestPath).toLowerCase(), // the full uri to the page
    {
        siteAbsoluteUrl: _spPageContextInfo.siteAbsoluteUrl.toLowerCase(),
        webAbsoluteUrl: _spPageContextInfo.webAbsoluteUrl.toLowerCase(),
        sharepointHealthScore: req.getResponseHeader('x-sharepointhealthscore'),
        sharepointCorrelationId: req.getResponseHeader('sprequestguid'),
        spiislatency: req.getResponseHeader('spiislatency'),
        statusCode: req.getResponseHeader('status')
    }
);

Step 3, collecting custom pageView data

Do you have an important metric you'd like to track when users traverse through your site? You can use this markup instead of Step 2 to get started collecting custom data.

appInsights.trackPageView(
    "my title",
    "https://mysite.skynorthsoftware.com/sites/coolsite",
    {
        customData = window.location.hostname,
        userName = localStorage.getItem("userName")
    }
);

Putting it all together

This is what the final result should look like. Once you save and deploy your changes to the site, you should see data trickling into the App Insights portal within a few minutes!

<script>
    var appInsights=window.appInsights||function(a){
        function b(a){c[a]=function(){var b=arguments;c.queue.push(function(){c[a].apply(c,b)})}}var c={config:a},d=document,e=window;setTimeout(function(){var b=d.createElement("script");b.src=a.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js",d.getElementsByTagName("script")[0].parentNode.appendChild(b)});try{c.cookie=d.cookie}catch(a){}c.queue=[];for(var f=["Event","Exception","Metric","PageView","Trace","Dependency"];f.length;)b("track"+f.pop());if(b("setAuthenticatedUserContext"),b("clearAuthenticatedUserContext"),b("startTrackEvent"),b("stopTrackEvent"),b("startTrackPage"),b("stopTrackPage"),b("flush"),!a.disableExceptionTracking){f="onerror",b("_"+f);var g=e[f];e[f]=function(a,b,d,e,h){var i=g&&g(a,b,d,e,h);return!0!==i&&c["_"+f](a,b,d,e,h),i}}return c
         }({
                instrumentationKey:"<guid-found-in-azure-portal>"
        });

    window.appInsights=appInsights;

    var req = new XMLHttpRequest();
    req.open('HEAD', document.location, false);
    req.send(null); 

    appInsights.trackPageView(
        _spPageContextInfo.webTitle,
        (window.location.protocol + "//" + window.location.hostname + _spPageContextInfo.serverRequestPath).toLowerCase(), // the full uri to the page
        {
            siteAbsoluteUrl: _spPageContextInfo.siteAbsoluteUrl.toLowerCase(),
            webAbsoluteUrl: _spPageContextInfo.webAbsoluteUrl.toLowerCase(),
            sharepointHealthScore: req.getResponseHeader('x-sharepointhealthscore'),
            sharepointCorrelationId: req.getResponseHeader('sprequestguid'),
            spiislatency: req.getResponseHeader('spiislatency'),
            statusCode: req.getResponseHeader('status'),
            customData = window.location.hostname,
            userName = localStorage.getItem("userName")
        }
    );
</script>

Mike Veazie

Mike is self motivated, goal oriented, and has a passion for learning. He loves being outside his comfort zone, and being involved on challenging projects.


comments powered by Disqus
Company Info

SkyNorth Software LLC
5357 Penn Ave South
Minneapolis, MN 55419

Follow Us

Get the latest news and updates.


© SkyNorth Software LLC