Application Insights javascript sdk 无法正常工作
Posted
技术标签:
【中文标题】Application Insights javascript sdk 无法正常工作【英文标题】:Application Insights javascript sdk not working 【发布时间】:2022-01-04 06:48:06 【问题描述】:我有一个 mvc5 应用程序,我想在应用程序洞察中启用服务器端和客户端日志记录。服务器端日志记录按预期工作正常,但问题出在客户端日志记录中。在布局页面中,我在此处提到的“head”标签中添加了以下脚本 (https://docs.microsoft.com/en-us/azure/azure-monitor/app/javascript)
<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),treturn 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:2var 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)trym.cookie=l.cookiecatch(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=!0return 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
// name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
// ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
// useXhr: 1, // Use XHR instead of fetch to report failures (if available),
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
// onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
cfg: // Application Insights Configuration
instrumentationKey: "InstrumentationKey"
/* ...Other Configuration Options... */
);
</script>
但问题是它不起作用。如果我在应用洞察中转到性能选项卡并转到浏览器选项卡,它是空的。我不确定我在这里做错了什么。
这是我的应用洞察配置文件
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
<InstrumentationKey>InstrumentationKey</InstrumentationKey>
<TelemetryInitializers>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureWebAppRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
<!-- Extended list of bots:
search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client-->
<Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters>
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.AzureAppServiceRoleNameFromHostNameHeaderInitializer, Microsoft.AI.Web" />
</TelemetryInitializers>
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
<ExcludeComponentCorrelationHttpHeadersOnDomains>
<!--
Requests to the following hostnames will not be modified by adding correlation headers.
Add entries here to exclude additional hostnames.
NOTE: this configuration will be lost upon NuGet upgrade.
-->
<Add>core.windows.net</Add>
<Add>core.chinacloudapi.cn</Add>
<Add>core.cloudapi.de</Add>
<Add>core.usgovcloudapi.net</Add>
</ExcludeComponentCorrelationHttpHeadersOnDomains>
<IncludeDiagnosticSourceActivities>
<Add>Microsoft.Azure.EventHubs</Add>
<Add>Microsoft.Azure.ServiceBus</Add>
</IncludeDiagnosticSourceActivities>
</Add>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule, Microsoft.AI.WindowsServer">
<!--
Remove individual fields collected here by adding them to the ApplicationInsighs.HeartbeatProvider
with the following syntax:
<Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights">
<ExcludedHeartbeatProperties>
<Add>osType</Add>
<Add>location</Add>
<Add>name</Add>
<Add>offer</Add>
<Add>platformFaultDomain</Add>
<Add>platformUpdateDomain</Add>
<Add>publisher</Add>
<Add>sku</Add>
<Add>version</Add>
<Add>vmId</Add>
<Add>vmSize</Add>
<Add>subscriptionId</Add>
<Add>resourceGroupName</Add>
<Add>placementGroupId</Add>
<Add>tags</Add>
<Add>vmScaleSetName</Add>
</ExcludedHeartbeatProperties>
</Add>
NOTE: exclusions will be lost upon upgrade.
-->
</Add>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer">
<!--</Add>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.FirstChanceExceptionStatisticsTelemetryModule, Microsoft.AI.WindowsServer">-->
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
<Handlers>
<!--
Add entries here to filter out additional handlers:
NOTE: handler configuration will be lost upon NuGet upgrade.
-->
<Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
<Add>System.Web.StaticFileHandler</Add>
<Add>System.Web.Handlers.AssemblyResourceLoader</Add>
<Add>System.Web.Optimization.BundleHandler</Add>
<Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
<Add>System.Web.Handlers.TraceHandler</Add>
<Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
<Add>System.Web.HttpDebugHandler</Add>
</Handlers>
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web" />
<Add Type="Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule, Microsoft.AI.Web" />
</TelemetryModules>
<ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
<TelemetrySinks>
<Add Name="default">
<TelemetryProcessors>
<Add Type="Motion.Kinetic.Infrastructure.Logging.AI.AzureStorageDependencyFilter, Infrastructure" />
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" />
<Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" />
</TelemetryProcessors>
<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel" />
</Add>
</TelemetrySinks>
<!--
Learn more about Application Insights configuration with ApplicationInsights.config here:
http://go.microsoft.com/fwlink/?LinkID=513840
Note: If not present, please add <InstrumentationKey>Your Key</InstrumentationKey> to the top of this file.
-->
<!--
Learn more about Application Insights configuration with ApplicationInsights.config here:
http://go.microsoft.com/fwlink/?LinkID=513840
Note: If not present, please add <InstrumentationKey>Your Key</InstrumentationKey> to the top of this file.
-->
<!--
Learn more about Application Insights configuration with ApplicationInsights.config here:
http://go.microsoft.com/fwlink/?LinkID=513840
Note: If not present, please add <InstrumentationKey>Your Key</InstrumentationKey> to the top of this file.
-->
</ApplicationInsights>
更新:
我也尝试添加更多配置选项,如下所示,但仍然没有成功。
cfg: // Application Insights Configuration
instrumentationKey: "InstrumentationKey",
enableDebug: true,
verboseLogging: true,
disableFetchTracking: false,
enableCorsCorrelation: true,
enableRequestHeaderTracking: true,
enableResponseHeaderTracking: true
此外,在“网络”选项卡中,我可以看到对“https://dc.services.visualstudio.com/v2/track”的跟踪调用,响应如下:
"itemsReceived":2,"itemsAccepted":0,"errors":["index":0,"statusCode":206,"message":"Telemetry sampled out.","index":1,"statusCode":206,"message":"Telemetry sampled out."],"appId":"my-app-id"
【问题讨论】:
【参考方案1】:我正在关注doc 在asp.net mvc
应用程序中实施应用程序洞察力。
您已经在 Views\Shared\_Layout.cshtml
和 appinsights.config
如果不是,请按照以下步骤操作:
打开 Views\Shared_Layout.cshtml
此文件是此应用程序呈现的 HTML 页面的最外层模板。 Application Insights 已在 head 标记内插入初始化代码,以便您可以立即开始使用 JavaScript API 来检测应用程序的客户端部分。在instrumentationKey中添加您的Application Insights密钥:“Your key here”这部分。
< 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),treturn 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:2var 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)trym.cookie=l.cookiecatch(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=!0return 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
// name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
// ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
// useXhr: 1, // Use XHR instead of fetch to report failures (if available),
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
// onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
cfg: // Application Insights Configuration
instrumentationKey: "Your key here"
/* ...Other Configuration Options... */
);
< /script>
打开 ApplicationInsights.config 文件并检查您的 application insights
标记/connectionString
标记,其中包含应用程序洞察检测密钥。
如果不是,您需要通过右键单击项目来配置 Azure application insights
,并在本地/Azure 配置您的应用程序洞察力。
默认情况下,它会在 ApplicationInsights.config 文件中添加您的应用程序洞察 连接字符串 标记
< ConnectionString> Your app insights connection string < /ConnectionString>
如果没有,您可以添加 Instrumentation
键标签
< InstrumentationKey> Your instrumentation key < /InstrumentationKey>
运行您的应用程序并在 application Insights 中查看结果
性能标签
如果您在本地添加了应用程序洞察力,请在 VS 中的应用程序洞察力按钮中查看结果
【讨论】:
如果回答对您有帮助,请Accept it as an Answer,以便遇到相同问题的其他人可以找到此解决方案并解决他们的问题。以上是关于Application Insights javascript sdk 无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章
ILogger 到 Application Insights