-
Notifications
You must be signed in to change notification settings - Fork 240
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[AI][Task]17099792: Add sample and doc to dependency plugin #1989
Merged
Merged
Changes from 4 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
7c8366f
add sample and doc to dependency plugin
Karlie-777 9d500ae
update dependency doc
Karlie-777 e2d81f8
update
Karlie-777 0854254
Merge branch 'master' into karlie/doc
Karlie-777 f26b89c
add aisku sample
Karlie-777 eca1c27
update
Karlie-777 5b57c27
Merge branch 'master' into karlie/doc
Karlie-777 0a37978
update examples
Karlie-777 03741c9
update
Karlie-777 4b9c053
update example links
Karlie-777 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
# Microsoft Application Insights JavaScript SDK - Dependencies Plugin | ||
|
||
|
||
|
||
Dependencies Plugin for the Application Insights Javascript SDK | ||
|
||
## Configuration | ||
|
||
[`ICorrelationConfig`](../../shared/AppInsightsCommon/src/Interfaces/ICorrelationConfig.ts) | ||
|
||
## Functions | ||
|
||
### Dependency Listeners | ||
|
||
`addDependencyListener(dependencyListener: DependencyListenerFunction): IDependencyListenerHandler` | ||
|
||
A [dependency listener](../API-reference.md#adddependencylistener) is a callback function that **allows you to perform additional manipulation of the request details before the request is performed**. | ||
|
||
This includes :- | ||
|
||
- Complete access to either the XMLHttpRequest instance or the fetch API `input` and `init` arguments. | ||
- Ability to get/set the properties used to generate the W3C `traceparent` header (`traceId`, `spanId,`traceFlags) | ||
- Set values in the object context container for other listeners called after the current one, as well as this context object is also made available to all dependency initializers. | ||
|
||
```javascript | ||
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(); | ||
``` | ||
|
||
### Dependency Initializers | ||
|
||
`addDependencyInitializer(dependencyInitializer: DependencyInitializerFunction): IDependencyInitializerHandler` | ||
|
||
A [Dependency Initializer](../API-reference.md#adddependencyinitializer) is very similar to a [Telemetry Initializer](https://github.com/Microsoft/ApplicationInsights-JS#telemetry-initializers) 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 :- | ||
|
||
- A Dependency Initializer is called "before" the event is processed by the pipeline, as such it will NOT (yet) contain the automatically populated properties that are applied later; | ||
- When a dependency initializer returns `false` to drop the event the event does NOT count against the `maxAjaxCallsPerView` as this blocks the event call from being tracked, and while returning `false` from a [Telemetry Initializer](https://github.com/Microsoft/ApplicationInsights-JS#telemetry-initializers) will also stop the event from being reported because this is further down the processing pipeline the dependency event IS counted against the `maxAjaxCallsPerView` limit. | ||
- It has access to an optional "context" `{ [key: string]: any }` object that is also available to the Dependency Listeners. This allows a listener to add additional details to the context (before the XHR/fetch request is sent), and the initializer will be called after the request has completed. | ||
|
||
```javascript | ||
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(); | ||
``` | ||
|
||
### Track Dependency | ||
|
||
`trackDependencyData(dependency:` `IDependencyTelemetry``, properties?: { [key: string]: any }): void` | ||
|
||
[TrackDependencyData](../API-reference.md#trackdependencydata) function allows you to manually log a dependency call. | ||
|
||
```javascript | ||
appInsights.trackDependencyData({absoluteUrl: 'some url', responseCode: 200, method: 'GET', id: 'some id'}); | ||
``` | ||
|
||
## Sample | ||
|
||
A [sample](./../samples/dependency/) is provided to show how to filter, modify, block and disable dependency data. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
# Application Insights JavaScript SDK | ||
|
||
## Dependency Sample | ||
|
||
This Sample shows how to filter, modify, block and disable dependency data with [`addDependencyListener`](../../API-reference.md#adddependencylistener) and [`addDependencyInitializer`](../../API-reference.md#adddependencyinitializer). | ||
|
||
## Sample Build | ||
|
||
- Locate to dependency sample folder root. | ||
- Run `tsc` to build the sample. | ||
- Replace `YOUR_CONNECTION_STRING` in `index.html` with your connection string. | ||
- Open `index.html` in a running server. | ||
|
||
## Description | ||
|
||
- button `add-handlers` will add a dependencyListener with the following changes: | ||
|
||
```javascript | ||
context.listener = "dependency-listener-context"; | ||
traceFlags = 0; | ||
``` | ||
|
||
and a dependencyInitializer with the following changes: | ||
|
||
```javascript | ||
item.name = "dependency-name"; | ||
item.properties.url = item.target; | ||
context.initializer = "dependency-initializer-context"; | ||
``` | ||
|
||
- button `stop-dependency-event` will block all dependency events. | ||
|
||
- button `remove-all-handlers` will remove all previously added dependency initializers and listeners. | ||
|
||
- button `create-fetch-request` will trigger a fetch request. | ||
|
||
- button `create-xhr-request` will trigger a xhr request. | ||
|
||
- button `untrack-fetch-request` will trigger a fetch request that will be blocked. | ||
|
||
## Contributing | ||
|
||
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit <https://cla.microsoft.com>. | ||
|
||
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA. | ||
|
||
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. | ||
|
||
## Data Collection | ||
|
||
As this SDK is designed to enable applications to perform data collection which is sent to the Microsoft collection endpoints the following is required to identify our privacy statement. | ||
|
||
The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft’s privacy statement. Our privacy statement is located at [here](https://go.microsoft.com/fwlink/?LinkID=824704). You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. | ||
|
||
## Trademarks | ||
|
||
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft’s Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies. | ||
|
||
## License | ||
|
||
MIT |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
<!DOCTYPE html> | ||
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="utf-8"> | ||
<title>Dependency Sample</title> | ||
<link rel="stylesheet" href="style/style.css"/> | ||
<script type="text/javascript"> | ||
var connectionString = "YOUR_CONNECTION_STRING"; | ||
const urlParams = new URLSearchParams(window.location.search); | ||
connectionString = urlParams.get("cs") || connectionString; | ||
</script> | ||
|
||
<script type="text/javascript">!function(T,l,y){var S=T.location,k="script",D="instrumentationKey",C="ingestionendpoint",I="disableExceptionTracking",E="ai.device.",b="toLowerCase",w="crossOrigin",N="POST",e="appInsightsSDK",t=y.name||"appInsights";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:"5",version:2,config:d};function v(e,t){var n={},a="Browser";return n[E+"id"]=a[b](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=""+e;return 1===t.length&&(t="0"+t),t}return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}(),iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,u,p,l;g=!0,m.queue=[],f||(f=!0,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(";"),a=0;a<n.length;a++){var i=n[a].split("=");2===i.length&&(e[i[0][b]()]=i[1])}if(!e[C]){var r=e.endpointsuffix,o=r?e.location:null;e[C]="https://"+(o?o+".":"")+"dc."+(r||"services.visualstudio.com")}return e}(),c=s[D]||d[D]||"",u=s[C],p=u?u+"/v2/track":d.endpointUrl,(l=[]).push((n="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=t,i=p,(o=(r=v(c,"Exception")).data).baseType="ExceptionData",o.baseData.exceptions=[{typeName:"SDKLoadFailed",message:n.replace(/\./g,"-"),hasFullStack:!1,stack:n+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(S&&S.pathname||"_unknown_")+"\nEndpoint: "+i,parsedStack:[]}],r)),l.push(function(e,t,n,a){var i=v(c,"Message"),r=i.data;r.baseType="MessageData";var o=r.baseData;return o.message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+n+")").replace(/\"/g,"")+'"',o.properties={endpoint:a},i}(0,0,t,p)),function(e,t){if(JSON){var n=T.fetch;if(n&&!y.useXhr)n(t,{method:N,body:JSON.stringify(e),mode:"cors"});else if(XMLHttpRequest){var a=new XMLHttpRequest;a.open(N,t),a.setRequestHeader("Content-type","application/json"),a.send(JSON.stringify(e))}}}(l,p))}function i(e,t){f||setTimeout(function(){!t&&m.core||a()},500)}var e=function(){var n=l.createElement(k);n.src=h;var e=y[w];return!e&&""!==e||"undefined"==n[w]||(n[w]=e),n.onload=i,n.onerror=a,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||i(0,t)},n}();y.ld<0?l.getElementsByTagName("head")[0].appendChild(e):setTimeout(function(){l.getElementsByTagName(k)[0].parentNode.appendChild(e)},y.ld||0)}try{m.cookie=l.cookie}catch(p){}function t(e){for(;e.length;)!function(t){m[t]=function(){var e=arguments;g||m.queue.push(function(){m[t].apply(m,e)})}}(e.pop())}var n="track",r="TrackPage",o="TrackEvent";t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+r,"stop"+r,"start"+o,"stop"+o,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),m.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4};var s=(d.extensionConfig||{}).ApplicationInsightsAnalytics||{};if(!0!==d[I]&&!0!==s[I]){var c="onerror";t(["_"+c]);var u=T[c];T[c]=function(e,t,n,a,i){var r=u&&u(e,t,n,a,i);return!0!==r&&m["_"+c]({message:e,url:t,lineNumber:n,columnNumber:a,error:i}),r},d.autoExceptionInstrumented=!0}return m}(y.cfg);function a(){y.onInit&&y.onInit(n)}(T[t]=n).queue&&0===n.queue.length?(n.queue.push(a),n.trackPageView({})):a()}(window,document,{ | ||
|
||
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", // The SDK URL Source for the CDN | ||
//src: "http://localhost:9001/AISKU/browser/ai.2.min.js", // The URL Source for the local build | ||
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag | ||
cfg: { // Application Insights Configuration | ||
connectionString: connectionString, | ||
}}); | ||
</script> | ||
|
||
</head> | ||
<body> | ||
<h1>Microsoft Application Insights JavaScript SDK - Dependencies</h1> | ||
<script src="./dist/dependency.js"></script> | ||
</body> | ||
</html> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This file moves dependency section to docs, will update main readme when this docs is merged