Skip to content

Commit

Permalink
Merge pull request #748 from Microsoft/users/piyalij/updatesAndDocs
Browse files Browse the repository at this point in the history
Update readme for how to update code snippet to load sdk v2. Bug fixes to allow v1 and v2 snippet to work correctly. Version updates.
  • Loading branch information
jpiyali authored Jan 12, 2019
2 parents 7b7b8ca + c4c6d53 commit 8223a75
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 21 deletions.
53 changes: 41 additions & 12 deletions AISKU/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,18 @@
description="Reference doc"
services="application-insights"
documentationCenter=".net"
authors="alancameronwills"
manager="douge"/>
authors="markwolff"/>

<tags
ms.service="application-insights"
ms.workload="tbd"
ms.tgt_pltfrm="ibiza"
ms.devlang="na"
ms.topic="article"
ms.date="08/24/2015"
ms.author="awills"/>
ms.date="08/24/2015"/>


# Application Insights JavaScript SDK - Web
# Application Insights JavaScript SDK (Beta SDK)

[![Build Status](https://dev.azure.com/mseng/AppInsights/_apis/build/status/AppInsights%20-%20DevTools/1DS%20JavaScript%20SDK%20-%20SKU%20Web)](https://dev.azure.com/mseng/AppInsights/_build/latest?definitionId=7760)
[![Build Status](https://travis-ci.org/Microsoft/ApplicationInsights-JS.svg?branch=master)](https://travis-ci.org/Microsoft/ApplicationInsights-JS)
Expand Down Expand Up @@ -56,12 +54,13 @@ appInsights.loadAppInsights();
### Snippet Setup (Ignore if using NPM)
If your app does not use NPM, you can directly instrument your webpages with Application Insights by pasting this snippet at the top of each your pages. Preferably, it should be the first script in your `<head>` section so that it can monitor any potential issues with all of your dependencies.
```html
<script type="text/javascript">
var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(n){var r={config:n,initialize:!0},i=document,e=window,t="script";setTimeout(function(){var e=i.createElement(t);e.src=n.url||"https://az416426.vo.msecnd.net/beta/ai.1.min.js",i.getElementsByTagName(t)[0].parentNode.appendChild(e)});try{r.cookie=i.cookie}catch(e){}function a(n){r[n]=function(){var e=arguments;r.queue.push(function(){r[n].apply(r,e)})}}r.queue=[];for(var c=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];c.length;)a("track"+c.pop());var o="TrackPage";if(a("start"+o),a("stop"+o),!(!0===n.disableExceptionTracking||n.extensionConfig&&n.extensionConfig.ApplicationInsightsAnalytics&&!0===n.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){a("_"+(c="onerror"));var s=e[c];e[c]=function(e,n,i,t,a){var o=s&&s(e,n,i,t,a);return!0!==o&&r["_"+c]({message:e,url:n,lineNumber:i,columnNumber:t,error:a}),o},n.autoExceptionInstrumented=!0}return r}(
{
<script type="text/javascript">
var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(e){function n(e){t[e]=function(){var n=arguments;t.queue.push(function(){t[e].apply(t,n)})}}var t={config:e};t.initialize=!0;var i=document,a=window;setTimeout(function(){var n=i.createElement("script");n.src=e.url||"https://az416426.vo.msecnd.net/beta/ai.1.min.js",i.getElementsByTagName("script")[0].parentNode.appendChild(n)});try{t.cookie=i.cookie}catch(e){}t.queue=[],t.version=2;
for(var r=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];r.length;)n("track"+r.pop());n("startTrackPage"),n("stopTrackPage");var o="Track"+r[0];
if(n("start"+o),n("stop"+o),!(!0===e.disableExceptionTracking||e.extensionConfig&&e.extensionConfig.ApplicationInsightsAnalytics&&!0===e.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){n("_"+(r="onerror"));var c=a[r];a[r]=function(e,n,i,a,o){var s=c&&c(e,n,i,a,o);return!0!==s&&t["_"+r]({message:e,url:n,lineNumber:i,columnNumber:a,error:o}),s},e.autoExceptionInstrumented=!0}return t}
({
instrumentationKey:"INSTRUMENTATION_KEY"
}
);if((window[aiName]=aisdk).queue&&0===aisdk.queue.length){var pageViewItem={name:document.title?document.title:"",uri:document.URL?document.URL:""};aisdk.trackPageView(pageViewItem)}
});if(window[aiName]=aisdk,aisdk.queue&&0===aisdk.queue.length){var pageViewItem={name:document.title?document.title:"",uri:document.URL?document.URL:""};aisdk.trackPageView(pageViewItem)}
</script>
```

Expand All @@ -75,6 +74,10 @@ appInsights.trackException({error: new Error('some error')}, customProperties);
appInsights.trackTrace({message: 'some trace'});
appInsights.trackMetric({name: 'some metric', average: 42});
appInsights.trackDependencyData({absoluteUrl: 'some url', resultCode: 200, method: 'GET', id: 'some id'});
appInsights.startTrackPage("pageName");
appInsights.stopTrackPage("pageName", {customProp1: "some value"});
appInsights.startTrackEvent("event");
appInsights.stopTrackEvent("event", {customProp1: "some value"});
```

### Setting Up Autocollection
Expand Down Expand Up @@ -152,15 +155,41 @@ Most configuration fields are named such that they can be defaulted to falsey. A

## Examples

For runnable examples, see our [Application Insights Demos Page](../Examples/)
For runnable examples, see [Application Insights Javascript SDK samples](https://github.com/Azure-Samples?utf8=%E2%9C%93&q=application+insights+sdk&type=&language=)

## Application Insights Web Basic

For a lightweight experience, you can instead install the basic version of Application Insights
```
npm i --save @microsoft/applicationinsights-web-basic
```
This version comes with the bare minimum amount of features and functionalities and relies on you to build it up as you see fit. For example, it performs no auto-collection (uncaught exceptions, ajax, etc). The APIs to send certain telemetry types, like `trackTrace`, `trackEvent`, etc, are not included in this version, so you will need to provide your own wrapper.
This version comes with the bare minimum amount of features and functionalities and relies on you to build it up as you see fit. For example, it performs no auto-collection (uncaught exceptions, ajax, etc). The APIs to send certain telemetry types, like `trackTrace`, `trackException`, etc, are not included in this version, so you will need to provide your own wrapper. The only api that is available is `track`.


## Application Insights Upgrading to New SDK Version
Breaking changes in the SDK V2 version:
- To allow for better api signatures, some of the apis such as trackPageView, trackException have been updated. Running in IE8 or lower versions of the browser is not supported.
- Telemetry envelope has some changes due to data schema updates.

If you are using the current application insights PRODUCTION SDK (1.0.20) and want to see if the new SDK works in runtime, please update URL depending on your current SDK loading scenario:

**a)** Download via CDN scenario:
Update code snippet that you currently use to point to the following URL:
```
"https://az416426.vo.msecnd.net/beta/ai.1.min.js"
```

**b)** NPM scenario:
Call downloadAndSetup to download full ApplicationInsights script from CDN and initialize it with instrumentation key.
```ts
appInsights.downloadAndSetup({

instrumentationKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
url: "https://az416426.vo.msecnd.net/beta/ai.1.min.js"
});
```

Test in internal environment to verify monitoring telemetry is working as expected. If all works, please update your api signatures appropriately to SDK V2 version and deploy in your production environments.

## Contributing

Expand Down
4 changes: 2 additions & 2 deletions AISKU/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"sideEffects": false,
"scripts": {
"clean": "rm -rfv browser types dist-esm",
"build": "npm run build:esm && npm run build:browser",
"build": "npm run build:esm && npm run build:browser && grunt snippetvnext",
"build:esm": "grunt aisku",
"build:browser": "rollup -c",
"test": "grunt aiskutests"
Expand All @@ -21,7 +21,7 @@
"typescript": "2.5.3"
},
"dependencies": {
"@microsoft/applicationinsights-analytics-js": "^1.0.0-beta.12",
"@microsoft/applicationinsights-analytics-js": "1.0.0-beta.13",
"@microsoft/applicationinsights-channel-js": "^1.0.0-beta.12",
"@microsoft/applicationinsights-common": "^1.0.0-beta.14",
"@microsoft/applicationinsights-core-js": "^1.0.0-beta.5",
Expand Down
1 change: 1 addition & 0 deletions AISKU/snippet/snippet.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 8 additions & 5 deletions AISKU/src/ApplicationInsightsContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,24 @@ import { Initialization as ApplicationInsights, Snippet, IApplicationInsights }

export class ApplicationInsightsContainer {

public static getAppInsights(snippet: Snippet, version: number = 2.0) : IApplicationInsights | IAppInsightsDeprecated {
public static getAppInsights(snippet: Snippet, version: number) : IApplicationInsights | IAppInsightsDeprecated {
let initialization = new ApplicationInsights(snippet);
let legacyMode = version === 2.0 ? false : true;
initialization.updateSnippetDefinitions(snippet);
initialization.loadAppInsights(legacyMode);
let legacyMode = version !== 2.0 ? true : false;

// Two target scenarios:
// 1. Customer runs v1 snippet + runtime. If customer updates just cdn location to new SDK, it will run in compat mode so old apis work
// 2. Customer updates to new snippet (that uses cdn location to new SDK. This is same as a new customer onboarding
// and all api signatures are expected to map to new SDK. Note new snippet specifies version

if (version === 2.0) {
initialization.updateSnippetDefinitions(snippet);
initialization.loadAppInsights(legacyMode);
return initialization; // default behavior with new snippet
} else {
return new AppInsightsDeprecated(snippet, initialization); // target scenario old snippet + updated endpoint
let legacy = new AppInsightsDeprecated(snippet, initialization); // target scenario old snippet + updated endpoint
legacy.updateSnippetDefinitions(snippet);
initialization.loadAppInsights(legacyMode);
return legacy;
}
}
}
10 changes: 10 additions & 0 deletions AISKU/src/ApplicationInsightsDeprecated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,16 @@ export class AppInsightsDeprecated implements IAppInsightsDeprecated {
throw new Error("downloadAndSetup not implemented in web SKU");
}

public updateSnippetDefinitions(snippet: Snippet) {
// apply full appInsights to the global instance
// Note: This must be called before loadAppInsights is called
for (var field in this) {
if (typeof field === 'string') {
snippet[field as string] = this[field];
}
}
}

// note: these are split into methods to enable unit tests
public loadAppInsights() {

Expand Down
2 changes: 1 addition & 1 deletion AISKU/src/Initialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export class Initialization implements IApplicationInsights {

this.properties = new PropertiesPlugin();
this.dependencies = new DependenciesPlugin();
this.core = new AppInsightsCore();

this.snippet = snippet;
this.config = config;
Expand Down Expand Up @@ -247,7 +248,6 @@ export class Initialization implements IApplicationInsights {
throw new Error("Extensions not allowed in legacy mode");
}

this.core = new AppInsightsCore();
let extensions = [];
let appInsightsChannel: Sender = new Sender();

Expand Down
2 changes: 1 addition & 1 deletion ApplicationInsights/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@microsoft/applicationinsights-analytics-js",
"version": "1.0.0-beta.12",
"version": "1.0.0-beta.13",
"description": "Microsoft Application Insights Javascript SDK apis",
"main": "dist/applicationinsights-analytics-js.js",
"module": "dist-esm/applicationinsights-analytics-js.js",
Expand Down

0 comments on commit 8223a75

Please sign in to comment.