适用于网页的 Application InsightsApplication Insights for web pages

了解网页或应用的性能和使用情况。Find out about the performance and usage of your web page or app. 如果将 Application Insights 添加到页面脚本,可以获取页面加载和 AJAX 调用的时间、浏览器异常和 AJAX 失败的计数和详细信息,以及用户和会话计数。If you add Application Insights to your page script, you get timings of page loads and AJAX calls, counts, and details of browser exceptions and AJAX failures, as well as users and session counts. 所有这些信息可按页面、客户端 OS 和浏览器版本、地理位置和其他维度细分。All these can be segmented by page, client OS and browser version, geo location, and other dimensions. 可以针对失败计数或页面加载缓慢情况设置警报。You can set alerts on failure counts or slow page loading. 并且通过在 JavaScript 代码中插入跟踪调用,可以跟踪网页应用程序的不同功能的使用情况。And by inserting trace calls in your JavaScript code, you can track how the different features of your web page application are used.

可以在任何网页中使用 Application Insights - 刚刚添加了 JavaScript 的简短片段。Application Insights can be used with any web pages - you just add a short piece of JavaScript. 如果 Web 服务是 JavaASP.NET,则你可以将服务器端 SDK 与客户端 JavaScript SDK 结合使用,以全方面地了解应用的性能。If your web service is Java or ASP.NET, you can use the server-side SDKs in conjunction with the client-side JavaScript SDK to get an end-to-end understanding of your app's performance.

添加 JavaScript SDKAdding the JavaScript SDK

重要

新的 Azure 区域要求使用连接字符串而不是检测密钥。New Azure regions require the use of connection strings instead of instrumentation keys. 连接字符串用于标识要与遥测数据关联的资源。Connection string identifies the resource that you want to associate your telemetry data with. 它还允许你修改可供你的资源将其用作遥测目标的终结点。It also allows you to modify the endpoints your resource will use as a destination for your telemetry. 你需要复制连接字符串,并将其添加到应用程序的代码或环境变量中。You will need to copy the connection string and add it to your application's code or to an environment variable.

  1. 首先需要一个 Application Insights 资源。First you need an Application Insights resource. 如果你尚未获得资源和检测密钥,请遵照有关创建新资源的说明If you don't already have a resource and instrumentation key, follow the create a new resource instructions.
  2. 复制你要将 JavaScript 遥测数据发送到的资源(从步骤 1)的检测密钥(也称为“iKey”)或连接字符串。你需要将该密钥添加到 Application Insights JavaScript SDK 的 instrumentationKeyconnectionString 设置。Copy the instrumentation key (also known as "iKey") or connection string for the resource where you want your JavaScript telemetry to be sent (from step 1.) You will add it to the instrumentationKey or connectionString setting of the Application Insights JavaScript SDK.
  3. 通过以下两个选项之一,将 Application Insights JavaScript SDK 添加到网页或应用:Add the Application Insights JavaScript SDK to your web page or app via one of the following two options:

重要

仅使用一种方法将 JavaScript SDK 添加到应用程序。Only use one method to add the JavaScript SDK to your application. 如果使用 NPM 安装程序,请不要使用代码片段,反之亦然。If you use the NPM Setup, don't use the Snippet and vice versa.

备注

NPM 安装程序会将 JavaScript SDK 作为依赖项安装到项目中,启用 IntelliSense,而代码片段则会在运行时获取 SDK。NPM Setup installs the JavaScript SDK as a dependency to your project, enabling IntelliSense, whereas the Snippet fetches the SDK at runtime. 两者都支持相同的功能。Both support the same features. 但是,需要更多自定义事件和配置的开发人员通常会选择 NPM 安装程序,而需要快速启用现成 Web 分析的用户则选择代码片段。However, developers who desire more custom events and configuration generally opt for NPM Setup whereas users looking for quick enablement of out-of-the-box web analytics opt for the Snippet.

基于 npm 的设置npm based setup

通过 NPM 安装。Install via NPM.

npm i --save @microsoft/applicationinsights-web

备注

Typings 已包含在此包中,因此无需安装单独的 typings 包 。Typings are included with this package, so you do not need to install a separate typings package.

import { ApplicationInsights } from '@microsoft/applicationinsights-web'

const appInsights = new ApplicationInsights({ config: {
  instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE'
  /* ...Other Configuration Options... */
} });
appInsights.loadAppInsights();
appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview

基于代码片段的设置Snippet based setup

如果应用不使用 npm,则可以通过直接使用 Application Insights 来检测网页:只需将此代码片段粘贴到每个页面的顶部即可。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. 最好是将它用作 <head> 节中的第一个脚本,以便它可以监视所有依赖项存在的任何潜在问题或任何 JavaScript 问题。Preferably, it should be the first script in your <head> section so that it can monitor any potential issues with all of your dependencies and optionally any JavaScript errors. 如果使用的是 Blazor Server 应用,请在文件 _Host.cshtml 的顶部 <head> 部分中添加代码片段。If you are using Blazor Server App, add the snippet at the top of the file _Host.cshtml in the <head> section.

为了帮助跟踪应用程序使用的代码片段版本,从版本 2.5.5 开始,页面视图事件将包含一个新的标记“ai.internal.snippet”,该标记将包含标识的代码片段版本。To assist with tracking which version of the snippet your application is using, starting from version 2.5.5 the page view event will include a new tag "ai.internal.snippet" that will contain the identified snippet version.

当前代码片段(下面列出)为版本“5”,该版本在代码片段中编码为 sv:"#",可在 GitHub 上找到当前版本The current Snippet (listed below) is version "5", the version is encoded in the snippet as sv:"#" and the current version is also available on GitHub.

<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
// 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:"INSTRUMENTATION_KEY",
      endpointUrl: "TelemetryChannel_Endpoint_Address"
}});
</script>

备注

为了提高可读性并减少可能的 JavaScript 错误,在上述代码片段的新行上列出了所有可能的配置选项,如果不希望更改注释行的值,可以将其删除。For readability and to reduce possible JavaScript errors, all of the possible configuration options are listed on a new line in snippet code above, if you don't want to change the value of a commented line it can be removed.

备注

你可以将 TelemetryChannel_Endpoint_Address 的占位符值替换为此文档中的 Azure 中国区域的实际终结点地址。You can replace the placeholder value for TelemetryChannel_Endpoint_Address with the actual endpoint address for Azure China region in this doc.

报告脚本加载失败Reporting Script load failures

此版本的代码片段检测并报告在将 SDK 作为扩展从 CDN 加载到 Azure Monitor 门户时出现的故障(在“故障”>“异常”>“浏览器”下),此异常提供此类故障的可见性,使你知道应用程序不会按预期方式报告遥测(或其他异常)。This version of the snippet detects and reports failures when loading the SDK from the CDN as an exception to the Azure Monitor portal (under the failures > exceptions > browser), this exception provides visibility into failures of this type so that you are aware that your application is not reporting telemetry (or other exceptions) as expected. 此信号对于了解以下情况至关重要:由于未加载或初始化 SDK,因此缺少遥测数据,这可能导致:This signal is an important measurement in understanding that you have lost telemetry because the SDK did not load or initialize which can lead to:

  • 漏报用户使用(或尝试使用)站点的方式;Under-reporting of how users are using (or trying to use) your site;
  • 缺少关于最终用户使用站点的方式的遥测数据;Missing telemetry on how your end users are using your site;
  • 遗漏可能阻止最终用户成功使用站点的 JavaScript 错误。Missing JavaScript errors that could potentially be blocking your end users from successfully using your site.

有关此异常的详细信息,请参阅 SDK 加载失败疑难解答页面。For details on this exception see the SDK load failure troubleshooting page.

将此失败作为门户异常进行报告时不会使用 Application Insights 配置中的 disableExceptionTracking 配置选项,因此,如果发生此失败,则将始终通过代码片段进行报告,即使禁用了 window.onerror 支持也是如此。Reporting of this failure as an exception to the portal does not use the configuration option disableExceptionTracking from the application insights configuration and therefore if this failure occurs it will always be reported by the snippet, even when the window.onerror support is disabled.

IE 8(或更低版本)尤其不支持报告 SDK 加载失败。Reporting of SDK load failures is specifically NOT supported on IE 8 (or less). 假设大多数环境都不仅仅是 IE 8 或更低版本,这有助于减少代码片段的缩小版大小。This assists with reducing the minified size of the snippet by assuming that most environments are not exclusively IE 8 or less. 如果你有此要求并且希望收到这些异常,则需要包括 fetch polyfill,或创建自己的代码片段版本,使其使用 XDomainRequest 而不是 XMLHttpRequest,建议使用提供的代码片段源代码作为起点。If you have this requirement and you wish to receive these exceptions, you will need to either include a fetch poly fill or create you own snippet version that uses XDomainRequest instead of XMLHttpRequest, it is recommended that you use the provided snippet source code as a starting point.

备注

如果你使用的是早期版本的代码片段,则强烈建议你更新到最新版本,以便收到以前未报告的问题。If you are using a previous version of the snippet, it is highly recommended that you update to the latest version so that you will receive these previously unreported issues.

代码片段配置选项Snippet configuration options

现在,所有配置选项都已移到脚本的末尾,以避免意外引入 JavaScript 错误,这类错误不仅会导致 SDK 加载失败,而且还会阻止报告此失败。All configuration options have now been move towards the end of the script to help avoid accidentally introducing JavaScript errors that would not just cause the SDK to fail to load, but also it would disable the reporting of the failure.

每个配置选项都会显示在一个新行上,如果不希望覆盖作为 [可选] 列出的项的默认值,则可以删除该行以最大程度地减小所返回页面的大小。Each configuration option is shown above on a new line, if you don't wish to override the default value of an item listed as [optional] you can remove that line to minimize the resulting size of your returned page.

可用配置有:The available configuration options are

名称Name 类型Type 说明Description
srcsrc 字符串 [必需]string [required] 要从中加载 SDK 的完整 URL。The full URL for where to load the SDK from. 此值用于动态添加的 <script /> 标记的“src”属性。This value is used for the "src" attribute of a dynamically added <script /> tag. 你可以使用公共 CDN 位置,也可以使用自己的私有托管位置。You can use the public CDN location or your own privately hosted one.
namename 字符串 [可选]string [optional] 已初始化的 SDK 的全局名称,默认值为 appInsightsThe global name for the initialized SDK, defaults to appInsights. 因此 window.appInsights 将是对已初始化实例的引用。So window.appInsights will be a reference to the initialized instance. 注意:如果提供一个名称值或上一个实例似乎是通过全局名称 appInsightsSDK 分配的,则此名称值也将在全局命名空间中定义为 window.appInsightsSDK=<name value>,SDK 初始化代码需要此名称,以确保它正在初始化和更新的代码片段主干和代理方法正确。Note: if you provide a name value or a previous instance appears to be assigned (via the global name appInsightsSDK) then this name value will also be defined in the global namespace as window.appInsightsSDK=<name value>, this is required by the SDK initialization code to ensure it's initializing and updating the correct snippet skeleton and proxy methods.
ldld 毫秒数 [可选]number in ms [optional] 定义在尝试加载 SDK 之前要等待的加载延迟。Defines the load delay to wait before attempting to load the SDK. 默认值为 0 毫秒,任何负值都表示将立即向页面的 <head> 区域添加脚本标记,然后在加载脚本(或失败)之前阻止页面加载事件。Default value is 0ms and any negative value will immediately add a script tag to the <head> region of the page, which will then block the page load event until to script is loaded (or fails).
useXhruseXhr 布尔 [可选]boolean [optional] 此设置仅用于报告 SDK 加载失败。This setting is used only for reporting SDK load failures. 报告将首先尝试使用 fetch()(如果可用),然后回退到 XHR,将此值设置为 true 即可绕过提取检查。Reporting will first attempt to use fetch() if available and then fallback to XHR, setting this value to true just bypasses the fetch check. 仅当在提取将无法发送失败事件的环境中使用应用程序时,才需要使用此值。Use of this value is only be required if your application is being used in an environment where fetch would fail to send the failure events.
crossOrigincrossOrigin 字符串 [可选]string [optional] 通过包含此设置,添加以下载 SDK 的脚本标记将包含带有此字符串值的 crossOrigin 属性。By including this setting, the script tag added to download the SDK will include the crossOrigin attribute with this string value. 如果未定义(默认值),则不添加 crossOrigin 属性。When not defined (the default) no crossOrigin attribute is added. 未定义建议的值(默认值);""; 或“anonymous”(如需了解所有有效值,请参阅 HTML 属性:crossorigin 文档)Recommended values are not defined (the default); ""; or "anonymous" (For all valid values see HTML attribute: crossorigin documentation)
cfgcfg 对象 [必需]object [required] 初始化期间传递到 Application Insights SDK 的配置。The configuration passed to the Application Insights SDK during initialization.

连接字符串设置Connection String Setup

对于 NPM 或代码片段设置,还可以使用连接字符串配置 Application Insights 的实例。For either the NPM or Snippet setup, you can also configure your instance of Application Insights using a Connection String. 只需将 instrumentationKey 字段替换为 connectionString 字段。Simply replace the instrumentationKey field with the connectionString field.

import { ApplicationInsights } from '@microsoft/applicationinsights-web'

const appInsights = new ApplicationInsights({ config: {
  connectionString: 'YOUR_CONNECTION_STRING_GOES_HERE'
  /* ...Other Configuration Options... */
} });
appInsights.loadAppInsights();
appInsights.trackPageView();

将遥测数据发送到 Azure 门户Sending telemetry to the Azure portal

默认情况下,Application Insights JavaScript SDK 会自动收集许多遥测项,这些项有助于确定应用程序和底层用户体验的运行状况。By default the Application Insights JavaScript SDK autocollects a number of telemetry items that are helpful in determining the health of your application and the underlying user experience. 其中包括:These include:

  • 应用中 未捕获到的异常,包括以下相关信息Uncaught exceptions in your app, including information on
    • 堆栈跟踪Stack trace
    • 异常详细信息和错误随附的消息Exception details and message accompanying the error
    • 错误的行号与列号Line & column number of error
    • 引发错误的 URLURL where error was raised
  • 应用发出的 网络依赖项请求XHRFETCH(默认已禁用提取集合)请求,包括以下相关信息Network Dependency Requests made by your app XHR and Fetch (fetch collection is disabled by default) requests, include information on
    • 依赖项源的 URLUrl of dependency source
    • 用于请求依赖项的命令和方法Command & Method used to request the dependency
    • 请求持续时间Duration of the request
    • 请求的结果代码和成功状态Result code and success status of the request
    • 发出请求的用户的 ID(如果有)ID (if any) of user making the request
    • 发出请求的关联上下文(如果有)Correlation context (if any) where request is made
  • 用户信息(例如位置、网络、IP)User information (for example, Location, network, IP)
  • 设备信息(例如,浏览器、OS、版本、语言、型号)Device information (for example, Browser, OS, version, language, model)
  • 会话信息Session information

遥测初始化表达式Telemetry initializers

遥测初始化表达式用于在从用户浏览器发送收集的遥测内容之前先对其进行修改。Telemetry initializers are used to modify the contents of collected telemetry before being sent from the user's browser. 它们还可用于返回 false 以阻止发送某些遥测数据。They can also be used to prevent certain telemetry from being sent, by returning false. 可将多个遥测初始化表达式添加到 Application Insights 实例,它们将按添加顺序执行。Multiple telemetry initializers can be added to your Application Insights instance, and they are executed in order of adding them.

addTelemetryInitializer 的输入参数是一个回调,该回调采用 ITelemetryItem 作为参数,并返回 booleanvoidThe input argument to addTelemetryInitializer is a callback that takes a ITelemetryItem as an argument and returns a boolean or void. 如果返回 false,则不发送遥测项,否则将继续处理下一个遥测初始化表达式(如果有),或者将遥测项发送到遥测集合终结点。If returning false, the telemetry item is not sent, else it proceeds to the next telemetry initializer, if any, or is sent to the telemetry collection endpoint.

使用遥测初始化表达式的示例:An example of using telemetry initializers:

var telemetryInitializer = (envelope) => {
  envelope.data.someField = 'This item passed through my telemetry initializer';
};
appInsights.addTelemetryInitializer(telemetryInitializer);
appInsights.trackTrace({message: 'This message will use a telemetry initializer'});

appInsights.addTelemetryInitializer(() => false); // Nothing is sent after this is executed
appInsights.trackTrace({message: 'this message will not be sent'}); // Not sent

配置Configuration

大多数配置字段的命名都可默认为 false。Most configuration fields are named such that they can be defaulted to false. instrumentationKey 以外的所有字段都是可选的。All fields are optional except for instrumentationKey.

名称Name 说明Description 默认Default
instrumentationKeyinstrumentationKey 必需Required
从 Azure 门户获取的检测密钥。Instrumentation key that you obtained from the Azure portal.
stringstring
NULLnull
accountIdaccountId 可选的帐户 ID(如果应用将用户分组到帐户中)。An optional account ID, if your app groups users into accounts. 不允许使用空格、逗号、分号、等于或竖线No spaces, commas, semicolons, equals, or vertical bars stringstring
NULLnull
sessionRenewalMssessionRenewalMs 如果用户处于非活动状态有这么长的时间(以毫秒为单位),则会记录会话。A session is logged if the user is inactive for this amount of time in milliseconds. numericnumeric
18000001800000
(30 分钟)(30 mins)
sessionExpirationMssessionExpirationMs 如果会话持续了这么长的时间(以毫秒为单位),则会记录会话。A session is logged if it has continued for this amount of time in milliseconds. numericnumeric
8640000086400000
(24 小时)(24 hours)
maxBatchSizeInBytesmaxBatchSizeInBytes 遥测批的最大大小。Max size of telemetry batch. 如果某个批超过此限制,则立即发送此批,并启动新批If a batch exceeds this limit, it is immediately sent and a new batch is started numericnumeric
1000010000
maxBatchIntervalmaxBatchInterval 发送前要批处理遥测数据的时间长短(毫秒)How long to batch telemetry for before sending (milliseconds) numericnumeric
1500015000
disable​ExceptionTrackingdisable​ExceptionTracking 如果为 true,则不自动收集异常。If true, exceptions are not autocollected. booleanboolean
falsefalse
disableTelemetrydisableTelemetry 如果为 true,则不收集或发送遥测数据。If true, telemetry is not collected or sent. booleanboolean
falsefalse
enableDebugenableDebug 如果为 true,则不管 SDK 日志记录设置如何,内部 调试数据都将引发为异常,而不是 记录这些数据。If true, internal debugging data is thrown as an exception instead of being logged, regardless of SDK logging settings. 默认值为 false。Default is false.
注意:如果启用此设置,每当发生内部错误时,都会导致遥测数据丢失。Note: Enabling this setting will result in dropped telemetry whenever an internal error occurs. 这可能有利于快速识别 SDK 的配置或用法问题。This can be useful for quickly identifying issues with your configuration or usage of the SDK. 如果你不希望在调试时丢失遥测数据,请考虑使用 consoleLoggingLeveltelemetryLoggingLevel,而不是 enableDebugIf you do not want to lose telemetry while debugging, consider using consoleLoggingLevel or telemetryLoggingLevel instead of enableDebug.
booleanboolean
falsefalse
loggingLevelConsoleloggingLevelConsole 内部 Application Insights 错误记录到控制台。Logs internal Application Insights errors to console.
0:关闭,0: off,
1:仅限严重错误,1: Critical errors only,
2:所有内容(错误和警告)2: Everything (errors & warnings)
numericnumeric
00
loggingLevelTelemetryloggingLevelTelemetry 内部 Application Insights 错误作为遥测数据发送。Sends internal Application Insights errors as telemetry.
0:关闭,0: off,
1:仅限严重错误,1: Critical errors only,
2:所有内容(错误和警告)2: Everything (errors & warnings)
numericnumeric
11
diagnosticLogIntervaldiagnosticLogInterval 内部日志记录队列的(内部)轮询间隔(以毫秒为单位)(internal) Polling interval (in ms) for internal logging queue numericnumeric
1000010000
samplingPercentagesamplingPercentage 要发送的事件百分比。Percentage of events that will be sent. 默认值为 100,表示发送所有事件。Default is 100, meaning all events are sent. 如果你希望避免大型应用程序达到数据上限,请设置此项。Set this if you wish to preserve your data cap for large-scale applications. numericnumeric
100100
autoTrackPageVisitTimeautoTrackPageVisitTime 如果为 true,则对于页面视图,将跟踪前一个检测的页面的查看时间并将其作为遥测数据发送,同时,为当前的页面视图启动新的计时器。If true, on a pageview, the previous instrumented page's view time is tracked and sent as telemetry and a new timer is started for the current pageview. booleanboolean
falsefalse
disableAjaxTrackingdisableAjaxTracking 如果为 true,则不自动收集 Ajax 调用。If true, Ajax calls are not autocollected. booleanboolean
falsefalse
disableFetchTrackingdisableFetchTracking 如果为 true,则不自动收集 Fetch 请求。If true, Fetch requests are not autocollected. booleanboolean
true
overridePageViewDurationoverridePageViewDuration 如果为 true,则在调用 trackPageView 时,trackPageView 的默认行为将更改为记录页面视图持续时间间隔的结束时间。If true, default behavior of trackPageView is changed to record end of page view duration interval when trackPageView is called. 如果为 false 且未为 trackPageView 提供自定义持续时间,则会使用导航计时 API 计算页面视图性能。If false and no custom duration is provided to trackPageView, the page view performance is calculated using the navigation timing API. booleanboolean
maxAjaxCallsPerViewmaxAjaxCallsPerView 默认值为 500 - 控制每个页面视图将监视多少个 Ajax 调用。Default 500 - controls how many Ajax calls will be monitored per page view. 设置为 -1 可监视页面上的所有(无限制)Ajax 调用。Set to -1 to monitor all (unlimited) Ajax calls on the page. numericnumeric
500500
disableDataLossAnalysisdisableDataLossAnalysis 如果为 false,则对于尚未发送的项,启动时将检查内部遥测发送方缓冲区。If false, internal telemetry sender buffers will be checked at startup for items not yet sent. booleanboolean
true
disable​CorrelationHeadersdisable​CorrelationHeaders 如果为 false,则 SDK 会将两个标头(“Request-Id”和“Request-Context”)添加到所有依赖项请求,以将其关联到服务器端上的对应请求。If false, the SDK will add two headers ('Request-Id' and 'Request-Context') to all dependency requests to correlate them with corresponding requests on the server side. booleanboolean
falsefalse
correlationHeader​ExcludedDomainscorrelationHeader​ExcludedDomains 禁用特定域的关联标头Disable correlation headers for specific domains string[]string[]
undefinedundefined
correlationHeader​ExcludePatternscorrelationHeader​ExcludePatterns 使用正则表达式禁用关联标头Disable correlation headers using regular expressions regex[]regex[]
undefinedundefined
correlationHeader​DomainscorrelationHeader​Domains 启用特定域的关联标头Enable correlation headers for specific domains string[]string[]
undefinedundefined
disableFlush​OnBeforeUnloaddisableFlush​OnBeforeUnload 如果为 true,则触发 onBeforeUnload 事件时不会调用 flush 方法If true, flush method will not be called when onBeforeUnload event triggers booleanboolean
falsefalse
enableSessionStorageBufferenableSessionStorageBuffer 如果为 true,则会将包含所有未发送的遥测数据的缓冲区存储在会话存储中。If true, the buffer with all unsent telemetry is stored in session storage. 加载页面时会还原该缓冲区The buffer is restored on page load booleanboolean
true
cookieCfgcookieCfg 启用 Cookie 使用的默认设置,请参阅 ICookieCfgConfig 设置,了解完整的默认值。Defaults to cookie usage enabled see ICookieCfgConfig settings for full defaults. ICookieCfgConfigICookieCfgConfig
(自 2.6.0 起)(Since 2.6.0)
undefinedundefined
isCookieUseDisabledisCookieUseDisabled
disableCookiesUsagedisableCookiesUsage
如果为 true,则 SDK 不会存储或读取 Cookie 中的任何数据。If true, the SDK will not store or read any data from cookies. 请注意,这会禁用用户和会话 Cookie,令使用情况边栏选项卡和体验无效。Note that this disables the User and Session cookies and renders the usage blades and experiences useless. isCookieUseDisable 已弃用,取而代之的是 disableCookiesUsage,当两者都提供时,则优先考虑 disableCookiesUsage。isCookieUseDisable is deprecated in favor of disableCookiesUsage, when both are provided disableCookiesUsage takes precedence.
(自 v2.6.0 起)此外,如果还定义了 cookieCfg.enabled,则其优先级高于这些值,Cookie 的使用可以在初始化后通过 core.getCookieMgr().setEnabled(true) 重新启用。(Since v2.6.0) And if cookieCfg.enabled is also defined it will take precedence over these values, Cookie usage can be re-enabled after initialization via the core.getCookieMgr().setEnabled(true).
cookieCfg.enabled 的别名alias for cookieCfg.enabled
falsefalse
cookieDomaincookieDomain 自定义 Cookie 域。Custom cookie domain. 若要跨子域共享 Application Insights Cookie,此字段会有帮助。This is helpful if you want to share Application Insights cookies across subdomains.
(自 v2.6.0 起)如果定义了 cookieCfg.domain,则其优先级高于此值。(Since v2.6.0) If cookieCfg.domain is defined it will take precedence over this value.
cookieCfg.domain 的别名alias for cookieCfg.domain
nullnull
cookiePathcookiePath 自定义 cookie 路径。Custom cookie path. 如果要在应用程序网关后共享 Application Insights cookie,这会很有帮助。This is helpful if you want to share Application Insights cookies behind an application gateway.
如果定义了 cookieCfg.path,则其优先级高于此值。If cookieCfg.path is defined it will take precedence over this value.
cookieCfg.path 的别名alias for cookieCfg.path
(自 2.6.0 起)(Since 2.6.0)
nullnull
isRetryDisabledisRetryDisabled 如果为 false,则出现代码 206(部分成功)、408(超时)、429(请求过多)、500(内部服务器错误)、503(服务不可用)和 0(脱机,仅当已检测到此状态时)时会重试If false, retry on 206 (partial success), 408 (timeout), 429 (too many requests), 500 (internal server error), 503 (service unavailable), and 0 (offline, only if detected) booleanboolean
falsefalse
isStorageUseDisabledisStorageUseDisabled 如果为 true,则 SDK 不会存储或读取本地和会话存储中的任何数据。If true, the SDK will not store or read any data from local and session storage. booleanboolean
falsefalse
isBeaconApiDisabledisBeaconApiDisabled 如果为 false,则 SDK 将使用信标 API 发送所有遥测数据If false, the SDK will send all telemetry using the Beacon API booleanboolean
true
onunloadDisableBeacononunloadDisableBeacon 选项卡关闭时,SDK 将使用信标 API 发送所有剩余的遥测When tab is closed, the SDK will send all remaining telemetry using the Beacon API booleanboolean
falsefalse
sdkExtensionsdkExtension 设置 SDK 扩展名。Sets the sdk extension name. 仅允许使用字母字符。Only alphabetic characters are allowed. 扩展名将添加为“ai.internal.sdkVersion”标记的前缀(例如“ext_javascript:2.0.0”)。The extension name is added as a prefix to the 'ai.internal.sdkVersion' tag (for example, 'ext_javascript:2.0.0'). stringstring
NULLnull
isBrowserLink​TrackingEnabledisBrowserLink​TrackingEnabled 如果为 true,则 SDK 将跟踪所有浏览器链接请求。If true, the SDK will track all Browser Link requests. booleanboolean
falsefalse
appIdappId appId 用于在客户端上发生的 AJAX 依赖项与服务器端请求之间进行关联。AppId is used for the correlation between AJAX dependencies happening on the client-side with the server-side requests. 启用信标 API 后,无法自动使用 appId,但可以在配置中手动设置它。When Beacon API is enabled, it cannot be used automatically, but can be set manually in the configuration. stringstring
NULLnull
enable​CorsCorrelationenable​CorsCorrelation 如果为 true,则 SDK 会将两个标头(“Request-Id”和“Request-Context”)添加到所有 CORS 请求,以将传出的 AJAX 依赖项关联到服务器端上的对应请求。If true, the SDK will add two headers ('Request-Id' and 'Request-Context') to all CORS requests to correlate outgoing AJAX dependencies with corresponding requests on the server side. booleanboolean
falsefalse
namePrefixnamePrefix 一个可选值,用作 localStorage 和 Cookie 名称的名称后缀。An optional value that will be used as name postfix for localStorage and cookie name. 字符串string
undefinedundefined
enable​AutoRoute​Trackingenable​AutoRoute​Tracking 自动跟踪单页应用程序 (SPA) 中的路由更改。Automatically track route changes in Single Page Applications (SPA). 如果为 true,则每次更改路由都会将一个新的页面视图发送到 Application Insights。If true, each route change will send a new Pageview to Application Insights. 哈希路由更改 (example.com/foo#bar) 也会记录为新的页面视图。Hash route changes (example.com/foo#bar) are also recorded as new page views. booleanboolean
falsefalse
enableRequest​HeaderTrackingenableRequest​HeaderTracking 如果为 true,则跟踪 AJAX & Fetch 请求标头。If true, AJAX & Fetch request headers is tracked. booleanboolean
falsefalse
enableResponse​HeaderTrackingenableResponse​HeaderTracking 如果为 true,则跟踪 AJAX & Fetch 请求的响应头。If true, AJAX & Fetch request's response headers is tracked. booleanboolean
falsefalse
distributedTracingModedistributedTracingMode 设置分布式跟踪模式。Sets the distributed tracing mode. 如果设置了 AI_AND_W3C 模式或 W3C 模式,则将生成 W3C 跟踪上下文标头 (traceparent/tracestate),并将其包含在所有传出请求中。If AI_AND_W3C mode or W3C mode is set, W3C trace context headers (traceparent/tracestate) will be generated and included in all outgoing requests. 提供 AI_AND_W3C 是为了与任何旧版 Application Insights 检测服务向后兼容。AI_AND_W3C is provided for back-compatibility with any legacy Application Insights instrumented services. 请参阅此处的示例。See example here. DistributedTracingModesDistributedTracingModesor
numericnumeric
(自 v2.6.0 起)DistributedTracingModes.AI_AND_W3C(Since v2.6.0) DistributedTracingModes.AI_AND_W3C
(v 2.5.11 或更早版本)DistributedTracingModes.AI(v2.5.11 or earlier) DistributedTracingModes.AI
enable​AjaxErrorStatusTextenable​AjaxErrorStatusText 如果为 true,则在 AJAX 请求失败时包含依赖关系事件中的响应错误数据文本。If true, include response error data text in dependency event on failed AJAX requests. booleanboolean
falsefalse
enable​AjaxPerfTrackingenable​AjaxPerfTracking 用于启用查找并包含报告的 ajax(XHR 和 fetch)报告的指标中其他浏览器 window.performance 计时的标记。Flag to enable looking up and including additional browser window.performance timings in the reported ajax (XHR and fetch) reported metrics. booleanboolean
falsefalse
maxAjaxPerf​LookupAttemptsmaxAjaxPerf​LookupAttempts 查找 window.performance 计时的最大次数,此值为必需,因为并非所有浏览器在报告 XHR 请求完成之前都会填充 window.performance,而对于 fetch 请求,将在请求完成之后添加该值。The maximum number of times to look for the window.performance timings (if available), this is required as not all browsers populate the window.performance before reporting the end of the XHR request and for fetch requests this is added after its complete. numericnumeric
33
ajaxPerfLookupDelayajaxPerfLookupDelay 重新尝试为 ajax 请求查找 windows.performance 计时时要等待的时间,时间以毫秒计并直接传递给 setTimeout()。The amount of time to wait before re-attempting to find the windows.performance timings for an ajax request, time is in milliseconds and is passed directly to setTimeout(). numericnumeric
25 毫秒25 ms
enableUnhandled​PromiseRejection​TrackingenableUnhandled​PromiseRejection​Tracking 如果为 true,则将自动收集未处理的拒绝承诺并报告为 JavaScript 错误。If true, unhandled promise rejections will be autocollected and reported as a JavaScript error. 如果 disableExceptionTracking 为 true(不跟踪异常),则将忽略配置值且不会报告未处理的拒绝承诺。When disableExceptionTracking is true (don't track exceptions), the config value will be ignored and unhandled promise rejections will not be reported. booleanboolean
falsefalse
disable​InstrumentationKey​Validationdisable​InstrumentationKey​Validation 如果为 true,则跳过检测密钥验证检查。If true, instrumentation key validation check is bypassed. booleanboolean
falsefalse
enablePerfMgrenablePerfMgr 启用时(为 true 时)将为已检测的代码创建本地 perfEvents 以发出 perfEvents(通过 doPerf() 帮助程序)。When enabled (true) this will create local perfEvents for code that has been instrumented to emit perfEvents (via the doPerf() helper). 这可用于根据使用情况识别 SDK 中的性能问题,或者选择性地在自己的已检测代码中识别性能问题。This can be used to identify performance issues within the SDK based on your usage or optionally within your own instrumented code. 基本文档中提供了更多详细信息More details are available by the basic documentation. 自 v2.5.7 起Since v2.5.7 booleanboolean
falsefalse
perfEvtsSendAllperfEvtsSendAll 如果已启用 enablePerfMgr 且 IPerfManager 触发了 INotificationManager.perfEvent(),此标志会确定是为所有事件触发事件并发送到所有侦听器(为 true 时),还是仅针对父级事件触发事件(为 false 时,<默认值>)。When enablePerfMgr is enabled and the IPerfManager fires a INotificationManager.perfEvent() this flag determines whether an event is fired (and sent to all listeners) for all events (true) or only for 'parent' events (false <default>).
父级 IPerfEvent 事件在创建时没有其他 IPerfEvent 仍在运行,且其“父级”属性不为 NULL 或未定义状态。A parent IPerfEvent is an event where no other IPerfEvent is still running at the point of this event being created and it's parent property is not null or undefined. 自 v2.5.7 起Since v2.5.7
booleanboolean
falsefalse
idLengthidLength 标识用于生成新的随机会话和用户 ID 值的默认长度。Identifies the default length used to generate new random session and user id values. 默认值为 22,以前的默认值为 5(v 2.5.8 或更低版本),如果需要保留以前的最大长度,则应将此值设置为 5。Defaults to 22, previous default value was 5 (v2.5.8 or less), if you need to keep the previous maximum length you should set this value to 5. numericnumeric
2222

从版本 2.6.0 开始,Cookie 管理功能现在可直接在实例中使用,并且可以在初始化后禁用和重新启用。From version 2.6.0, cookie management is now available directly from the instance and can be disabled and re-enabled after initialization.

如果在初始化期间通过 disableCookiesUsagecookieCfg.enabled 配置禁用了该功能,现在可以使用 ICookieMgr setEnabled 函数重新启用。If disabled during initialization via the disableCookiesUsage or cookieCfg.enabled configurations, you can now re-enable via the ICookieMgr setEnabled function.

基于实例的 Cookie 管理还替代了 disableCookies()setCookie(...)getCookie(...)deleteCookie(...) 之前的 CoreUtils 全局函数。The instance based cookie management also replaces the previous CoreUtils global functions of disableCookies(), setCookie(...), getCookie(...) and deleteCookie(...). 另外,要从版本 2.6.0 中引入的摇树增强功能中受益,应不再使用全局函数。And to benefit from the tree-shaking enhancements also introduced as part of version 2.6.0 you should no longer uses the global functions.

ICookieMgrConfigICookieMgrConfig

基于实例的 Cookie 管理的 Cookie 配置,添加在版本 2.6.0 中。Cookie Configuration for instance based cookie management added in version 2.6.0.

名称Name 说明Description 类型和默认值Type and Default
enabledenabled 一个布尔,指示当前实例是否让 SDK 使用 Cookie。A boolean that indicates whether the use of cookies by the SDK is enabled by the current instance. 如果为 false,则此配置所初始化的 SDK 实例将不会存储或读取 Cookie 中的任何数据If false, the instance of the SDK initialized by this configuration will not store or read any data from cookies booleanboolean
true
domain 自定义 Cookie 域。Custom cookie domain. 若要跨子域共享 Application Insights Cookie,此字段会有帮助。This is helpful if you want to share Application Insights cookies across subdomains. 如果未提供,则使用根 cookieDomain 值中的值。If not provided uses the value from root cookieDomain value. stringstring
NULLnull
pathpath 指定用于 Cookie 的路径,如果未提供,将使用根 cookiePath 值中的任意值。Specifies the path to use for the cookie, if not provided it will use any value from the root cookiePath value. 字符串string
/
getCookiegetCookie 用于提取命名 Cookie 值的函数,如果未提供,将使用内部 Cookie 解析/缓存。Function to fetch the named cookie value, if not provided it will use the internal cookie parsing / caching. (name: string) => string
nullnull
setCookiesetCookie 用于设置具有指定值的命名 Cookie 的函数,仅在添加或更新 Cookie 时调用。Function to set the named cookie with the specified value, only called when adding or updating a cookie. (name: string, value: string) => void
nullnull
delCookiedelCookie 用于删除具有指定值的命名 Cookie 的函数,与 setCookie 分离,从而无需分析值以确定是否添加或删除 Cookie。Function to delete the named cookie with the specified value, separated from setCookie to avoid the need to parse the value to determine whether the cookie is being added or removed. 如果未提供,则使用内部 cookie 解析/缓存。If not provided it will use the internal cookie parsing / caching. (name: string, value: string) => void
nullnull

启用“页面访问时间”跟踪Enable time-on-page tracking

通过设置 autoTrackPageVisitTime: true,跟踪用户在每个页面上花费的时间。By setting autoTrackPageVisitTime: true, the time a user spends on each page is tracked. 在每个新的 PageView 上,用户在上一页花费的时间将作为名为 PageVisitTime 的自定义指标发送。On each new PageView, the duration the user spent on the previous page is sent as a custom metric named PageVisitTime. 此自定义指标可在指标资源管理器中作为“基于日志的指标”查看。This custom metric is viewable in the Metrics Explorer as a "log-based metric".

启用关联Enable Correlation

关联功能会生成并发送启用分布式跟踪的数据,并为应用程序映射端到端事务查看和其他诊断工具提供支持。Correlation generates and sends data that enables distributed tracing and powers the application map, end-to-end transaction view, and other diagnostic tools.

下面的示例展示了启用关联功能所需的所有可能的配置,并且下方提供了特定于方案的说明:The following example shows all possible configurations required to enable correlation, with scenario-specific notes below:

// excerpt of the config section of the JavaScript SDK snippet with correlation
// between client-side AJAX and server requests enabled.
cfg: { // Application Insights Configuration
    instrumentationKey: "YOUR_INSTRUMENTATION_KEY_GOES_HERE"
    disableFetchTracking: false,
    enableCorsCorrelation: true,
    enableRequestHeaderTracking: true,
    enableResponseHeaderTracking: true,
    correlationHeaderExcludedDomains: ['myapp.chinacloudsites.cn', '*.queue.core.chinacloudapi.cn']
    /* ...Other Configuration Options... */
}});
</script>

如果与客户端通信的任何第三方服务器都不接受 Request-IdRequest-Context 标头,并且你无法更新其配置,则需要通过 correlationHeaderExcludeDomains 配置属性将其放入排除列表中。If any of your third-party servers that the client communicates with cannot accept the Request-Id and Request-Context headers, and you cannot update their configuration, then you'll need to put them into an exclude list via the correlationHeaderExcludeDomains configuration property. 此属性支持通配符。This property supports wildcards.

服务器端需要能够接受与所示的这些标头的连接。The server-side needs to be able to accept connections with those headers present. 根据服务器端的 Access-Control-Allow-Headers 配置,通常你需要通过手动添加 Request-IdRequest-Context 来扩展服务器端列表。Depending on the Access-Control-Allow-Headers configuration on the server-side it is often necessary to extend the server-side list by manually adding Request-Id and Request-Context.

Access-Control-Allow-Headers:Request-IdRequest-Context<your header>Access-Control-Allow-Headers: Request-Id, Request-Context, <your header>

备注

如果使用的是 2020 年发布的 OpenTelemtry 或 Application Insights SAK 或更高版本,我们建议使用 WC3 TraceContextIf you are using OpenTelemtry or Application Insights SDKs released in 2020 or later, we recommend using WC3 TraceContext. 请参阅此处的配置指南。See configuration guidance here.

单页应用程序Single Page Applications

默认情况下,此 SDK 不会 处理单页应用程序中发生的基于状态的路由更改。By default, this SDK will not handle state-based route changing that occurs in single page applications. 若要为单页应用程序启用自动路由更改跟踪,可将 enableAutoRouteTracking: true 添加到设置配置。To enable automatic route change tracking for your single page application, you can add enableAutoRouteTracking: true to your setup configuration.

目前,我们提供了一个单独的 React 插件(可以使用此 SDK 对其进行初始化)。Currently, we offer a separate React plugin, which you can initialize with this SDK. 该插件也能为你实现路由更改跟踪,并可收集其他特定于 React 的遥测数据。It will also accomplish route change tracking for you, as well as collect other React specific telemetry.

备注

仅当你不使用 React 插件时,才使用 enableAutoRouteTracking: trueUse enableAutoRouteTracking: true only if you are not using the React plugin. 当路由更改时,这两种方法都能发送新的 PageView。Both are capable of sending new PageViews when the route changes. 如果这两种方法均已启用,则可能会发送重复的 PageView。If both are enabled, duplicate PageViews may be sent.

扩展Extensions

扩展Extensions
ReactReact
React NativeReact Native
AngularAngular
单击“分析自动收集”Click Analytics Auto-collection

浏览浏览器/客户端数据Explore browser/client-side data

可以转到“指标”并添加你感兴趣的各个指标,来查看浏览器/客户端数据:Browser/client-side data can be viewed by going to Metrics and adding individual metrics you are interested in:

Application Insights“指标”页的屏幕截图,其中显示了 Web 应用程序指标数据的图形显示。

还可以通过门户中的“浏览器”体验查看 JavaScript SDK 中的数据。You can also view your data from the JavaScript SDK via the Browser experience in the portal.

选择“浏览器”,然后选择“失败”或“性能”。Select Browser and then choose Failures or Performance.

Application Insights“浏览器”页的屏幕截图,其中显示了如何将浏览器故障或浏览器性能添加到可以为 Web 应用程序查看的指标中。

性能Performance

Application Insights“性能”页的屏幕截图,其中显示了 Web 应用程序操作指标的图形显示。

依赖项Dependencies

Application Insights“性能”页的屏幕截图,其中显示了 Web 应用程序依赖项指标的图形显示。

分析Analytics

若要查询 JavaScript SDK 收集的遥测数据,请选择“在日志(分析)中查看”按钮。To query your telemetry collected by the JavaScript SDK, select the View in Logs (Analytics) button. 如果添加 client_Type == "Browser"where 语句,则只会看到来自 JavaScript SDK 的数据,而其他 SDK 收集的任何服务器端遥测数据将被排除。By adding a where statement of client_Type == "Browser", you will only see data from the JavaScript SDK and any server-side telemetry collected by other SDKs will be excluded.

// average pageView duration by name
let timeGrain=5m;
let dataset=pageViews
// additional filters can be applied here
| where timestamp > ago(1d)
| where client_Type == "Browser" ;
// calculate average pageView duration for all pageViews
dataset
| summarize avg(duration) by bin(timestamp, timeGrain)
| extend pageView='Overall'
// render result in a chart
| render timechart

源映射支持Source Map Support

可以在 Azure 门户中取消缩小异常遥测的已缩小调用堆栈。The minified callstack of your exception telemetry can be unminified in the Azure portal. “异常详细信息”面板中的所有现有集成将适用于最近取消缩小的调用堆栈。All existing integrations on the Exception Details panel will work with the newly unminified callstack.

可以将 Application Insights 资源链接到自己的 Azure Blob 存储容器,以便自动取消缩小调用堆栈。You can link your Application Insights resource to your own Azure Blob Storage container to automatically unminify call stacks. 若要开始,请参阅自动源映射支持To get started, see automatic source map support.

拖放Drag and drop

  1. 请在 Azure 门户中选择一个异常遥测项,以查看其“端到端事务详细信息”Select an Exception Telemetry item in the Azure portal to view its "End-to-end transaction details"
  2. 确定哪些源映射对应于此调用堆栈。Identify which source maps correspond to this call stack. 源映射必须与堆栈帧的源文件相匹配,但后缀为 .mapThe source map must match a stack frame's source file, but suffixed with .map
  3. 将源映射拖放到 Azure 门户 中的调用堆栈上 该动画图像显示了如何将源映射文件从生成文件夹拖放到 Azure 门户的“调用堆栈”窗口中。Drag and drop the source maps onto the call stack in the Azure portal An animated image showing how to drag and drop source map files from a build folder into the Call Stack window in the Azure portal.

Application Insights Web 基本版Application Insights Web Basic

若要获得精简的体验,可以改为安装基本版 Application InsightsFor 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 number of features and functionalities and relies on you to build it up as you see fit. 例如,它不执行自动收集(未捕获的异常、AJAX 等等)。For example, it performs no autocollection (uncaught exceptions, AJAX, etc.). 此版本不包含用于发送某些遥测类型的 API(例如 trackTracetrackException 等),因此你需要提供自己的包装器。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. 提供的唯一 API 是 trackThe only API that is available is track. 此处提供了一个示例。A sample is located here.

示例Examples

如需查看可运行的示例,请参阅 Application Insights JavaScript SDK 示例For runnable examples, see Application Insights JavaScript SDK Samples.

从旧版 Application Insights 升级Upgrading from the old version of Application Insights

SDK V2 版本中的重大更改:Breaking changes in the SDK V2 version:

  • 为了让用户生成更好的 API 签名,某些 API 调用(例如 trackPageView 和 trackException)已更新。To allow for better API signatures, some of the API calls, such as trackPageView and trackException, have been updated. 不支持在 Internet Explorer 8 和早期版本的浏览器中运行。Running in Internet Explorer 8 and earlier versions of the browser is not supported.
  • 由于数据架构更新,遥测信封的字段名称和结构已更改。The telemetry envelope has field name and structure changes due to data schema updates.
  • 已将 context.operation 转移到 context.telemetryTraceMoved context.operation to context.telemetryTrace. 此外还更改了一些字段 (operation.id --> telemetryTrace.traceID)。Some fields were also changed (operation.id --> telemetryTrace.traceID).
    • 若要手动刷新当前页面视图 ID(例如,在 SPA 应用中这样做),请使用 appInsights.properties.context.telemetryTrace.traceID = Microsoft.ApplicationInsights.Telemetry.Util.generateW3CId()To manually refresh the current pageview ID (for example, in SPA apps), use appInsights.properties.context.telemetryTrace.traceID = Microsoft.ApplicationInsights.Telemetry.Util.generateW3CId().

      备注

      为了使跟踪 ID 独一无二,以前使用 Util.newId(),现在使用 Util.generateW3CId()To keep the trace ID unique, where you previously used Util.newId(), now use Util.generateW3CId(). 二者最终都会成为操作 ID。Both ultimately end up being the operation ID.

如果你正在使用最新的 Application Insights PRODUCTION SDK (1.0.20),并想要查看新 SDK 是否可在运行时中正常工作,请根据当前的 SDK 加载方案更新 URL。If you're using the current application insights PRODUCTION SDK (1.0.20) and want to see if the new SDK works in runtime, update the URL depending on your current SDK loading scenario.

  • 通过 CDN 方案下载:更新当前用于指向以下 URL 的代码片段:Download via CDN scenario: Update the code snippet that you currently use to point to the following URL:

    "https://js.monitor.azure.com/scripts/b/ai.2.min.js"
    
  • npm 方案:调用 downloadAndSetup 以从 CDN 下载完整的 ApplicationInsights 脚本,并使用检测密钥将其初始化:npm scenario: Call downloadAndSetup to download the full ApplicationInsights script from CDN and initialize it with instrumentation key:

    appInsights.downloadAndSetup({
       instrumentationKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
       url: "https://js.monitor.azure.com/scripts/b/ai.2.min.jss"
       });
    

在内部环境中进行测试,以验证是否可按预期方式监视遥测。Test in internal environment to verify monitoring telemetry is working as expected. 如果一切正常,请相应地将 API 签名更新为 SDK V2 版本,并部署到生产环境中。If all works, update your API signatures appropriately to SDK V2 version and deploy in your production environments.

SDK 性能/开销SDK performance/overhead

经过 gzip 压缩后只有 36 KB,只需大约 15 毫秒即可完成初始化,Application Insights 在网站中的加载时间可忽略不计。At just 36 KB gzipped, and taking only ~15 ms to initialize, Application Insights adds a negligible amount of loadtime to your website. 使用代码片段时,很快就能加载极少量的库组件。By using the snippet, minimal components of the library are quickly loaded. 同时,整个脚本将在后台下载。In the meantime, the full script is downloaded in the background.

从 CDN 下载脚本时,页面的所有跟踪将会排队。While the script is downloading from the CDN, all tracking of your page is queued. 在下载的脚本以异步方式完成初始化后,将会跟踪已排队的所有事件。Once the downloaded script finishes asynchronously initializing, all events that were queued are tracked. 因此,在页面的整个生命周期内,你都不会丢失任何遥测数据。As a result, you will not lose any telemetry during the entire life cycle of your page. 此设置过程可为页面提供一个无缝分析系统,而用户察觉不到该系统。This setup process provides your page with a seamless analytics system, invisible to your users.

摘要:Summary:

  • npm 版本
  • gzip 压缩大小
  • 总初始化时间为 15 毫秒15 ms overall initialization time
  • 在页面的整个生命周期内都 不会 失去跟踪Zero tracking missed during life cycle of page

浏览器支持Browser support

Chrome Firefox IE Opera Safari
Chrome 最新版 ✔Chrome Latest ✔ Firefox 最新版 ✔Firefox Latest ✔ IE 9 + 和 Microsoft Edge ✔IE 9+ & Edge ✔
IE 8- 兼容IE 8- Compatible
Opera 最新版 ✔Opera Latest ✔ Safari 最新版 ✔Safari Latest ✔

ES3/IE8 兼容性ES3/IE8 Compatibility

作为 SDK,很多用户无法控制其客户所使用的浏览器。As an SDK there are numerous users that cannot control the browsers that their customers use. 因此,我们需要确保此 SDK 继续“工作”,并且在由旧版浏览器加载时不会中断 JS 执行。As such we need to ensure that this SDK continues to "work" and does not break the JS execution when loaded by an older browser. 虽然可以选择不支持 IE8 和旧版生成 (ES3) 浏览器,但有很多大型客户/用户会继续要求页面“工作”,并且我们发现,他们可能或无法控制其最终用户选择使用的浏览器。While it would be ideal to not support IE8 and older generation (ES3) browsers, there are numerous large customers/users that continue to require pages to "work" and as noted they may or cannot control which browser that their end users choose to use.

这并不意味着我们只支持最少的一组常见功能,只是我们需要维护 ES3 代码兼容性,并且需要采用一种既不会中断 ES3 JavaScript 分析又可作为可选功能进行添加的方式来添加新功能。This does NOT mean that we will only support the lowest common set of features, just that we need to maintain ES3 code compatibility and when adding new features they will need to be added in a manner that would not break ES3 JavaScript parsing and added as an optional feature.

有关 IE8 支持的完整详细信息,请参阅 GitHubSee GitHub for full details on IE8 support

开源 SDKOpen-source SDK

Application Insights JavaScript SDK 是开源的,用户可查看其源代码;若要对该项目做贡献,请访问官方 GitHub 存储库The Application Insights JavaScript SDK is open-source to view the source code or to contribute to the project visit the official GitHub repository.

有关最新的更新和 bug 修复,请参阅发行说明For the latest updates and bug fixes consult the release notes.

后续步骤Next steps