Skip to content

Commit 4b27411

Browse files
author
Kai Nawroth
committed
Changing code samples and formatting
1 parent 2ca2a24 commit 4b27411

File tree

3 files changed

+207
-205
lines changed

3 files changed

+207
-205
lines changed

articles/azure-monitor/app/api-filtering-sampling.md

Lines changed: 64 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,8 @@ Insert this snippet in ApplicationInsights.config:
9292
```xml
9393
<TelemetryProcessors>
9494
<Add Type="WebApplication9.SuccessfulDependencyFilter, WebApplication9">
95-
<!-- Set public property -->
96-
<MyParamFromConfigFile>2-beta</MyParamFromConfigFile>
95+
<!-- Set public property -->
96+
<MyParamFromConfigFile>2-beta</MyParamFromConfigFile>
9797
</Add>
9898
</TelemetryProcessors>
9999
```
@@ -148,10 +148,10 @@ Filter out bots and web tests. Although Metrics Explorer gives you the option to
148148
```csharp
149149
public void Process(ITelemetry item)
150150
{
151-
if (!string.IsNullOrEmpty(item.Context.Operation.SyntheticSource)) {return;}
152-
153-
// Send everything else:
154-
this.Next.Process(item);
151+
if (!string.IsNullOrEmpty(item.Context.Operation.SyntheticSource)) {return;}
152+
153+
// Send everything else:
154+
this.Next.Process(item);
155155
}
156156
```
157157

@@ -214,19 +214,18 @@ To learn more about telemetry processors and their implementation in Java, refer
214214

215215
1. Create a telemetry initializer callback function. The callback function takes `ITelemetryItem` as a parameter, which is the event that's being processed. Returning `false` from this callback results in the telemetry item to be filtered out.
216216

217-
```JS
218-
var filteringFunction = (envelope) => {
219-
if (envelope.data.someField === 'tobefilteredout') {
220-
return false;
221-
}
222-
223-
return true;
224-
};
225-
```
217+
```js
218+
var filteringFunction = (envelope) => {
219+
if (envelope.data.someField === 'tobefilteredout') {
220+
return false;
221+
}
222+
return true;
223+
};
224+
```
226225

227226
2. Add your telemetry initializer callback:
228227

229-
```JS
228+
```js
230229
appInsights.addTelemetryInitializer(filteringFunction);
231230
```
232231

@@ -255,27 +254,27 @@ namespace MvcWebRole.Telemetry
255254
* behavior of treating response codes >= 400 as failed requests
256255
*
257256
*/
258-
public class MyTelemetryInitializer : ITelemetryInitializer
259-
{
260-
public void Initialize(ITelemetry telemetry)
257+
public class MyTelemetryInitializer : ITelemetryInitializer
261258
{
262-
var requestTelemetry = telemetry as RequestTelemetry;
263-
// Is this a TrackRequest() ?
264-
if (requestTelemetry == null) return;
265-
int code;
266-
bool parsed = Int32.TryParse(requestTelemetry.ResponseCode, out code);
267-
if (!parsed) return;
268-
if (code >= 400 && code < 500)
259+
public void Initialize(ITelemetry telemetry)
269260
{
270-
// If we set the Success property, the SDK won't change it:
271-
requestTelemetry.Success = true;
272-
273-
// Allow us to filter these requests in the portal:
274-
requestTelemetry.Properties["Overridden400s"] = "true";
261+
var requestTelemetry = telemetry as RequestTelemetry;
262+
// Is this a TrackRequest() ?
263+
if (requestTelemetry == null) return;
264+
int code;
265+
bool parsed = Int32.TryParse(requestTelemetry.ResponseCode, out code);
266+
if (!parsed) return;
267+
if (code >= 400 && code < 500)
268+
{
269+
// If we set the Success property, the SDK won't change it:
270+
requestTelemetry.Success = true;
271+
272+
// Allow us to filter these requests in the portal:
273+
requestTelemetry.Properties["Overridden400s"] = "true";
274+
}
275+
// else leave the SDK to set the Success property
275276
}
276-
// else leave the SDK to set the Success property
277277
}
278-
}
279278
}
280279
```
281280

@@ -313,9 +312,9 @@ ASP.NET **Core/Worker service apps: Load your initializer**
313312
For apps written using [ASP.NET Core](asp-net-core.md#add-telemetryinitializers) or [WorkerService](worker-service.md#add-telemetry-initializers), adding a new telemetry initializer is done by adding it to the Dependency Injection container, as shown. Accomplish this step in the `Startup.ConfigureServices` method.
314313

315314
```csharp
316-
using Microsoft.ApplicationInsights.Extensibility;
317-
using CustomInitializer.Telemetry;
318-
public void ConfigureServices(IServiceCollection services)
315+
using Microsoft.ApplicationInsights.Extensibility;
316+
using CustomInitializer.Telemetry;
317+
public void ConfigureServices(IServiceCollection services)
319318
{
320319
services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();
321320
}
@@ -330,37 +329,38 @@ Insert a telemetry initializer by adding the onInit callback function in the [Ja
330329
<!-- IMPORTANT: If you're updating this code example, please remember to also update it in: 1) articles\azure-monitor\app\javascript-sdk.md and 2) articles\azure-monitor\app\javascript-feature-extensions.md -->
331330
```html
332331
<script type="text/javascript">
333-
!(function (cfg){function e(){cfg.onInit&&cfg.onInit(i)}var S,u,D,t,n,i,C=window,x=document,w=C.location,I="script",b="ingestionendpoint",E="disableExceptionTracking",A="ai.device.";"instrumentationKey"[S="toLowerCase"](),u="crossOrigin",D="POST",t="appInsightsSDK",n=cfg.name||"appInsights",(cfg.name||C[t])&&(C[t]=n),i=C[n]||function(l){var d=!1,g=!1,f={initialize:!0,queue:[],sv:"7",version:2,config:l};function m(e,t){var n={},i="Browser";function a(e){e=""+e;return 1===e.length?"0"+e:e}return n[A+"id"]=i[S](),n[A+"type"]=i,n["ai.operation.name"]=w&&w.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(f.sv||f.version),{time:(i=new Date).getUTCFullYear()+"-"+a(1+i.getUTCMonth())+"-"+a(i.getUTCDate())+"T"+a(i.getUTCHours())+":"+a(i.getUTCMinutes())+":"+a(i.getUTCSeconds())+"."+(i.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}},ver:4,seq:"1",aiDataContract:undefined}}var h=-1,v=0,y=["js.monitor.azure.com","js.cdn.applicationinsights.io","js.cdn.monitor.azure.com","js0.cdn.applicationinsights.io","js0.cdn.monitor.azure.com","js2.cdn.applicationinsights.io","js2.cdn.monitor.azure.com","az416426.vo.msecnd.net"],k=l.url||cfg.src;if(k){if((n=navigator)&&(~(n=(n.userAgent||"").toLowerCase()).indexOf("msie")||~n.indexOf("trident/"))&&~k.indexOf("ai.3")&&(k=k.replace(/(\/)(ai\.3\.)([^\d]*)$/,function(e,t,n){return t+"ai.2"+n})),!1!==cfg.cr)for(var e=0;e<y.length;e++)if(0<k.indexOf(y[e])){h=e;break}var i=function(e){var a,t,n,i,o,r,s,c,p,u;f.queue=[],g||(0<=h&&v+1<y.length?(a=(h+v+1)%y.length,T(k.replace(/^(.*\/\/)([\w\.]*)(\/.*)$/,function(e,t,n,i){return t+y[a]+i})),v+=1):(d=g=!0,o=k,c=(p=function(){var e,t={},n=l.connectionString;if(n)for(var i=n.split(";"),a=0;a<i.length;a++){var o=i[a].split("=");2===o.length&&(t[o[0][S]()]=o[1])}return t[b]||(e=(n=t.endpointsuffix)?t.location:null,t[b]="https://"+(e?e+".":"")+"dc."+(n||"services.visualstudio.com")),t}()).instrumentationkey||l.instrumentationKey||"",p=(p=p[b])?p+"/v2/track":l.endpointUrl,(u=[]).push((t="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",n=o,r=p,(s=(i=m(c,"Exception")).data).baseType="ExceptionData",s.baseData.exceptions=[{typeName:"SDKLoadFailed",message:t.replace(/\./g,"-"),hasFullStack:!1,stack:t+"\nSnippet failed to load ["+n+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(w&&w.pathname||"_unknown_")+"\nEndpoint: "+r,parsedStack:[]}],i)),u.push((s=o,t=p,(r=(n=m(c,"Message")).data).baseType="MessageData",(i=r.baseData).message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+s+")").replace(/\"/g,"")+'"',i.properties={endpoint:t},n)),o=u,c=p,JSON&&((r=C.fetch)&&!cfg.useXhr?r(c,{method:D,body:JSON.stringify(o),mode:"cors"}):XMLHttpRequest&&((s=new XMLHttpRequest).open(D,c),s.setRequestHeader("Content-type","application/json"),s.send(JSON.stringify(o))))))},a=function(e,t){g||setTimeout(function(){!t&&f.core||i()},500),d=!1},T=function(e){var n=x.createElement(I),e=(n.src=e,cfg[u]);return!e&&""!==e||"undefined"==n[u]||(n[u]=e),n.onload=a,n.onerror=i,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||a(0,t)},cfg.ld&&cfg.ld<0?x.getElementsByTagName("head")[0].appendChild(n):setTimeout(function(){x.getElementsByTagName(I)[0].parentNode.appendChild(n)},cfg.ld||0),n};T(k)}try{f.cookie=x.cookie}catch(p){}function t(e){for(;e.length;)!function(t){f[t]=function(){var e=arguments;d||f.queue.push(function(){f[t].apply(f,e)})}}(e.pop())}var r,s,n="track",o="TrackPage",c="TrackEvent",n=(t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+o,"stop"+o,"start"+c,"stop"+c,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),f.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},(l.extensionConfig||{}).ApplicationInsightsAnalytics||{});return!0!==l[E]&&!0!==n[E]&&(t(["_"+(r="onerror")]),s=C[r],C[r]=function(e,t,n,i,a){var o=s&&s(e,t,n,i,a);return!0!==o&&f["_"+r]({message:e,url:t,lineNumber:n,columnNumber:i,error:a,evt:C.event}),o},l.autoExceptionInstrumented=!0),f}(cfg.cfg),(C[n]=i).queue&&0===i.queue.length?(i.queue.push(e),i.trackPageView({})):e();})({
334-
src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js",
335-
crossOrigin: "anonymous",
336-
onInit: function (sdk) {
337-
sdk.addTelemetryInitializer(function (envelope) {
338-
envelope.data = envelope.data || {};
339-
envelope.data.someField = 'This item passed through my telemetry initializer';
340-
});
341-
}, // Once the application insights instance has loaded and initialized this method will be called
342-
cfg: { // Application Insights Configuration
343-
connectionString: "YOUR_CONNECTION_STRING"
344-
}});
332+
!(function (cfg){function e(){cfg.onInit&&cfg.onInit(n)}var x,w,D,t,E,n,C=window,O=document,b=C.location,q="script",I="ingestionendpoint",L="disableExceptionTracking",j="ai.device.";"instrumentationKey"[x="toLowerCase"](),w="crossOrigin",D="POST",t="appInsightsSDK",E=cfg.name||"appInsights",(cfg.name||C[t])&&(C[t]=E),n=C[E]||function(g){var f=!1,m=!1,h={initialize:!0,queue:[],sv:"8",version:2,config:g};function v(e,t){var n={},i="Browser";function a(e){e=""+e;return 1===e.length?"0"+e:e}return n[j+"id"]=i[x](),n[j+"type"]=i,n["ai.operation.name"]=b&&b.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(h.sv||h.version),{time:(i=new Date).getUTCFullYear()+"-"+a(1+i.getUTCMonth())+"-"+a(i.getUTCDate())+"T"+a(i.getUTCHours())+":"+a(i.getUTCMinutes())+":"+a(i.getUTCSeconds())+"."+(i.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}},ver:undefined,seq:"1",aiDataContract:undefined}}var n,i,t,a,y=-1,T=0,S=["js.monitor.azure.com","js.cdn.applicationinsights.io","js.cdn.monitor.azure.com","js0.cdn.applicationinsights.io","js0.cdn.monitor.azure.com","js2.cdn.applicationinsights.io","js2.cdn.monitor.azure.com","az416426.vo.msecnd.net"],o=g.url||cfg.src,r=function(){return s(o,null)};function s(d,t){if((n=navigator)&&(~(n=(n.userAgent||"").toLowerCase()).indexOf("msie")||~n.indexOf("trident/"))&&~d.indexOf("ai.3")&&(d=d.replace(/(\/)(ai\.3\.)([^\d]*)$/,function(e,t,n){return t+"ai.2"+n})),!1!==cfg.cr)for(var e=0;e<S.length;e++)if(0<d.indexOf(S[e])){y=e;break}var n,i=function(e){var a,t,n,i,o,r,s,c,u,l;h.queue=[],m||(0<=y&&T+1<S.length?(a=(y+T+1)%S.length,p(d.replace(/^(.*\/\/)([\w\.]*)(\/.*)$/,function(e,t,n,i){return t+S[a]+i})),T+=1):(f=m=!0,s=d,!0!==cfg.dle&&(c=(t=function(){var e,t={},n=g.connectionString;if(n)for(var i=n.split(";"),a=0;a<i.length;a++){var o=i[a].split("=");2===o.length&&(t[o[0][x]()]=o[1])}return t[I]||(e=(n=t.endpointsuffix)?t.location:null,t[I]="https://"+(e?e+".":"")+"dc."+(n||"services.visualstudio.com")),t}()).instrumentationkey||g.instrumentationKey||"",t=(t=(t=t[I])&&"/"===t.slice(-1)?t.slice(0,-1):t)?t+"/v2/track":g.endpointUrl,t=g.userOverrideEndpointUrl||t,(n=[]).push((i="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",o=s,u=t,(l=(r=v(c,"Exception")).data).baseType="ExceptionData",l.baseData.exceptions=[{typeName:"SDKLoadFailed",message:i.replace(/\./g,"-"),hasFullStack:!1,stack:i+"\nSnippet failed to load ["+o+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(b&&b.pathname||"_unknown_")+"\nEndpoint: "+u,parsedStack:[]}],r)),n.push((l=s,i=t,(u=(o=v(c,"Message")).data).baseType="MessageData",(r=u.baseData).message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+l+")").replace(/\"/g,"")+'"',r.properties={endpoint:i},o)),s=n,c=t,JSON&&((u=C.fetch)&&!cfg.useXhr?u(c,{method:D,body:JSON.stringify(s),mode:"cors"}):XMLHttpRequest&&((l=new XMLHttpRequest).open(D,c),l.setRequestHeader("Content-type","application/json"),l.send(JSON.stringify(s)))))))},a=function(e,t){m||setTimeout(function(){!t&&h.core||i()},500),f=!1},p=function(e){var n=O.createElement(q),e=(n.src=e,t&&(n.integrity=t),n.setAttribute("data-ai-name",E),cfg[w]);return!e&&""!==e||"undefined"==n[w]||(n[w]=e),n.onload=a,n.onerror=i,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||a(0,t)},cfg.ld&&cfg.ld<0?O.getElementsByTagName("head")[0].appendChild(n):setTimeout(function(){O.getElementsByTagName(q)[0].parentNode.appendChild(n)},cfg.ld||0),n};p(d)}cfg.sri&&(n=o.match(/^((http[s]?:\/\/.*\/)\w+(\.\d+){1,5})\.(([\w]+\.){0,2}js)$/))&&6===n.length?(d="".concat(n[1],".integrity.json"),i="@".concat(n[4]),l=window.fetch,t=function(e){if(!e.ext||!e.ext[i]||!e.ext[i].file)throw Error("Error Loading JSON response");var t=e.ext[i].integrity||null;s(o=n[2]+e.ext[i].file,t)},l&&!cfg.useXhr?l(d,{method:"GET",mode:"cors"}).then(function(e){return e.json()["catch"](function(){return{}})}).then(t)["catch"](r):XMLHttpRequest&&((a=new XMLHttpRequest).open("GET",d),a.onreadystatechange=function(){if(a.readyState===XMLHttpRequest.DONE)if(200===a.status)try{t(JSON.parse(a.responseText))}catch(e){r()}else r()},a.send())):o&&r();try{h.cookie=O.cookie}catch(k){}function e(e){for(;e.length;)!function(t){h[t]=function(){var e=arguments;f||h.queue.push(function(){h[t].apply(h,e)})}}(e.pop())}var c,u,l="track",d="TrackPage",p="TrackEvent",l=(e([l+"Event",l+"PageView",l+"Exception",l+"Trace",l+"DependencyData",l+"Metric",l+"PageViewPerformance","start"+d,"stop"+d,"start"+p,"stop"+p,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),h.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},(g.extensionConfig||{}).ApplicationInsightsAnalytics||{});return!0!==g[L]&&!0!==l[L]&&(e(["_"+(c="onerror")]),u=C[c],C[c]=function(e,t,n,i,a){var o=u&&u(e,t,n,i,a);return!0!==o&&h["_"+c]({message:e,url:t,lineNumber:n,columnNumber:i,error:a,evt:C.event}),o},g.autoExceptionInstrumented=!0),h}(cfg.cfg),(C[E]=n).queue&&0===n.queue.length?(n.queue.push(e),n.trackPageView({})):e();})({
333+
src: "https://js.monitor.azure.com/scripts/b/ai.3.gbl.min.js",
334+
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
335+
onInit: function (sdk) {
336+
sdk.addTelemetryInitializer(function (envelope) {
337+
envelope.data = envelope.data || {};
338+
envelope.data.someField = 'This item passed through my telemetry initializer';
339+
});
340+
}, // Once the application insights instance has loaded and initialized this method will be called
341+
// sri: false, // Custom optional value to specify whether fetching the snippet from integrity file and do integrity check
342+
cfg: { // Application Insights Configuration
343+
connectionString: "YOUR_CONNECTION_STRING"
344+
}});
345345
</script>
346346
```
347347
348348
#### [npm package](#tab/npmpackage)
349349
350-
```js
351-
import { ApplicationInsights } from '@microsoft/applicationinsights-web'
352-
353-
const appInsights = new ApplicationInsights({ config: {
354-
connectionString: 'YOUR_CONNECTION_STRING'
355-
/* ...Other Configuration Options... */
356-
} });
357-
appInsights.loadAppInsights();
358-
// To insert a telemetry initializer, uncomment the following code.
359-
/** var telemetryInitializer = (envelope) => { envelope.data = envelope.data || {}; envelope.data.someField = 'This item passed through my telemetry initializer';
360-
};
361-
appInsights.addTelemetryInitializer(telemetryInitializer); **/
362-
appInsights.trackPageView();
363-
```
350+
```js
351+
import { ApplicationInsights } from '@microsoft/applicationinsights-web'
352+
353+
const appInsights = new ApplicationInsights({ config: {
354+
connectionString: 'YOUR_CONNECTION_STRING'
355+
/* ...Other Configuration Options... */
356+
} });
357+
appInsights.loadAppInsights();
358+
// To insert a telemetry initializer, uncomment the following code.
359+
/** var telemetryInitializer = (envelope) => { envelope.data = envelope.data || {}; envelope.data.someField = 'This item passed through my telemetry initializer';
360+
};
361+
appInsights.addTelemetryInitializer(telemetryInitializer); **/
362+
appInsights.trackPageView();
363+
```
364364
365365
---
366366
@@ -486,8 +486,8 @@ The following sample initializer adds a custom property to every tracked telemet
486486
```csharp
487487
public void Initialize(ITelemetry item)
488488
{
489-
var itemProperties = item as ISupportProperties;
490-
if(itemProperties != null && !itemProperties.Properties.ContainsKey("customProp"))
489+
var itemProperties = item as ISupportProperties;
490+
if(itemProperties != null && !itemProperties.Properties.ContainsKey("customProp"))
491491
{
492492
itemProperties.Properties["customProp"] = "customValue";
493493
}

0 commit comments

Comments
 (0)