您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

Java Web 项目中的 Application Insights 入门Get started with Application Insights in a Java web project

Application Insights 是为 Web 开发人员提供的可扩展分析服务,可帮助你了解实时应用程序的性能和使用情况。Application Insights is an extensible analytics service for web developers that helps you understand the performance and usage of your live application. 使用它可自动检测请求、跟踪依赖项和收集性能计数器, 诊断性能问题和异常, 并编写代码来跟踪用户对应用执行的操作。Use it to automatically instrument request, track dependencies, and collect performance counters, diagnose performance issues and exceptions, and write code to track what users do with your app.

概述示例数据的屏幕截图

Application Insights 支持 Linux、Unix 或 Windows 上运行的 Java 应用。Application Insights supports Java apps running on Linux, Unix, or Windows.

需要:You need:

1.获取 Application Insights 检测密钥1. Get an Application Insights instrumentation key

  1. 登录到 Microsoft Azure 门户Sign in to the Microsoft Azure portal.

  2. 创建 Application Insights 资源。Create an Application Insights resource. 将应用程序类型设置为 Java Web 应用程序。Set the application type to Java web application.

  3. 查找新资源的检测密钥。Find the instrumentation key of the new resource. 稍后需要将此密钥粘贴到代码项目中。You'll need to paste this key into your code project shortly.

    在新资源概述中,单击“属性”,并复制检测密钥

2.将用于 Java 的 Application Insights SDK 添加到项目2. Add the Application Insights SDK for Java to your project

为项目选择适当的方式。Choose the appropriate way for your project.

如果使用 Maven... If you're using Maven...

如果项目已设置为使用 Maven 进行生成,请将以下代码合并到 pom.xml 文件。If your project is already set up to use Maven for build, merge the following code to your pom.xml file.

然后刷新项目依赖项,以下载库。Then, refresh the project dependencies to get the binaries downloaded.

    <dependencies>
      <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>applicationinsights-web-auto</artifactId>
        <!-- or applicationinsights-web for manual web filter registration -->
        <!-- or applicationinsights-core for bare API -->
        <version>2.5.0</version>
      </dependency>
    </dependencies>

如果使用 Gradle... If you're using Gradle...

如果项目已设置为使用 Gradle 进行生成,请将以下代码合并到 build.gradle 文件。If your project is already set up to use Gradle for build, merge the following code to your build.gradle file.

然后刷新项目依赖项,以下载库。Then refresh the project dependencies to get the binaries downloaded.

    dependencies {
      compile group: 'com.microsoft.azure', name: 'applicationinsights-web-auto', version: '2.5.0'
      // or applicationinsights-web for manual web filter registration
      // or applicationinsights-core for bare API
    }

否则,如果是手动管理依赖项...Otherwise, if you are manually managing dependencies ...

请下载最新版本,将所需文件复制到项目中,替换以前的版本。Download the latest version and copy the necessary files into your project, replacing any previous versions.

问题...Questions...

  • -web-auto组件-core之间-web的关系是什么?What's the relationship between the -web-auto, -web and -core components?

    • applicationinsights-web-auto通过在运行时自动注册 Application Insights servlet 筛选器, 提供跟踪 HTTP servlet 请求计数和响应时间的指标。applicationinsights-web-auto gives you metrics that track HTTP servlet request counts and response times, by automatically registering the Application Insights servlet filter at runtime.
    • applicationinsights-web还提供了跟踪 HTTP servlet 请求计数和响应时间的指标, 但需要在应用程序中手动注册 Application Insights servlet 筛选器。applicationinsights-web also gives you metrics that track HTTP servlet request counts and response times, but requires manual registration of the Application Insights servlet filter in your application.
    • applicationinsights-core仅为你提供了一个简单的 API, 例如, 你的应用程序不是基于 servlet 的。applicationinsights-core gives you just the bare API, for example, if your application is not servlet-based.
  • 应怎样将 SDK 更新到最新版本?How should I update the SDK to the latest version?

3.添加 ApplicationInsights.xml 文件3. Add an ApplicationInsights.xml file

在项目中的 resources 文件夹中添加 ApplicationInsights.xml,或确保将其添加到项目的部署类路径。Add ApplicationInsights.xml to the resources folder in your project, or make sure it is added to your project’s deployment class path. 将以下 XML 复制到其中。Copy the following XML into it.

替换为从 Azure 门户获取的检测密钥。Substitute the instrumentation key that you got from the Azure portal.

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings" schemaVersion="2014-05-30">

   <!-- The key from the portal: -->
   <InstrumentationKey>** Your instrumentation key **</InstrumentationKey>

   <!-- HTTP request component (not required for bare API) -->
   <TelemetryModules>
      <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebRequestTrackingTelemetryModule"/>
      <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebSessionTrackingTelemetryModule"/>
      <Add type="com.microsoft.applicationinsights.web.extensibility.modules.WebUserTrackingTelemetryModule"/>
   </TelemetryModules>

   <!-- Events correlation (not required for bare API) -->
   <!-- These initializers add context data to each event -->
   <TelemetryInitializers>
      <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebOperationIdTelemetryInitializer"/>
      <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebOperationNameTelemetryInitializer"/>
      <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebSessionTelemetryInitializer"/>
      <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebUserTelemetryInitializer"/>
      <Add type="com.microsoft.applicationinsights.web.extensibility.initializers.WebUserAgentTelemetryInitializer"/>
   </TelemetryInitializers>

</ApplicationInsights>

也可将配置文件置于可以通过应用程序进行访问的任何位置。Optionally, the configuration file can reside in any location accessible to your application. 系统属性 -Dapplicationinsights.configurationDirectory 指定 ApplicationInsights.xml 所在的目录。The system property -Dapplicationinsights.configurationDirectory specifies the directory that contains ApplicationInsights.xml. 例如,位于 E:\myconfigs\appinsights\ApplicationInsights.xml 的配置文件可以通过属性 -Dapplicationinsights.configurationDirectory="E:\myconfigs\appinsights" 进行配置。For example, a configuration file located at E:\myconfigs\appinsights\ApplicationInsights.xml would be configured with the property -Dapplicationinsights.configurationDirectory="E:\myconfigs\appinsights".

  • 检测密钥随遥测的每个项一起发送,并告知 Application Insights 在资源中显示它。The instrumentation key is sent along with every item of telemetry and tells Application Insights to display it in your resource.
  • HTTP 请求组件是可选的。The HTTP Request component is optional. 它自动将请求和响应时间的遥测数据发送到门户。It automatically sends telemetry about requests and response times to the portal.
  • 事件关联是对 HTTP 请求组件的补充。Event correlation is an addition to the HTTP request component. 它将标识符分配到服务器收到的每个请求,并将此标识符添加为遥测的每个项的“Operation.Id”属性。It assigns an identifier to each request received by the server, and adds this identifier as a property to every item of telemetry as the property 'Operation.Id'. 使用它可以通过在诊断搜索中设置筛选器,来关联与每个请求关联的遥测。It allows you to correlate the telemetry associated with each request by setting a filter in diagnostic search.

设置检测密钥的替代方法Alternative ways to set the instrumentation key

Application Insights SDK 按以下顺序查找密钥:Application Insights SDK looks for the key in this order:

  1. 系统属性:-DAPPINSIGHTS_INSTRUMENTATIONKEY = your_ikeySystem property: -DAPPINSIGHTS_INSTRUMENTATIONKEY=your_ikey
  2. 环境变量:APPINSIGHTS_INSTRUMENTATIONKEYEnvironment variable: APPINSIGHTS_INSTRUMENTATIONKEY
  3. 配置文件:ApplicationInsights.xmlConfiguration file: ApplicationInsights.xml

也可以 在代码中设置方法You can also set it in code:

    String instrumentationKey = "00000000-0000-0000-0000-000000000000";

    if (instrumentationKey != null)
    {
        TelemetryConfiguration.getActive().setInstrumentationKey(instrumentationKey);
    }

4.添加代理4. Add agent

安装 Java 代理以捕获传出 HTTP 调用、JDBC 查询、应用程序日志记录和更好的操作命名。Install the Java Agent to capture outgoing HTTP calls, JDBC queries, application logging, and better operation naming.

5.运行应用程序5. Run your application

在开发计算机上以调试模式运行应用程序,或将其发布到服务器。Either run it in debug mode on your development machine, or publish to your server.

6.在 Application Insights 中查看遥测数据6. View your telemetry in Application Insights

返回 Microsoft Azure 门户中的 Application Insights 资源。Return to your Application Insights resource in Microsoft Azure portal.

“概述”边栏选项卡中显示了 HTTP 请求数据。HTTP requests data appears on the overview blade. (如果未显示,请稍候片刻,并单击“刷新”。)(If it isn't there, wait a few seconds and then click Refresh.)

概述示例数据的屏幕截图

了解有关指标的详细信息。Learn more about metrics.

单击任一图表可查看详细聚合指标。Click through any chart to see more detailed aggregated metrics.

带有图表的“Application Insights 故障”窗格

实例数据Instance data

单击特定的请求类型可查看各个实例。Click through a specific request type to see individual instances.

钻取到特定示例视图

分析:功能强大的查询语言Analytics: Powerful query language

随着累积的数据越来越多,可以运行查询来聚合数据以及查找单个实例。As you accumulate more data, you can run queries both to aggregate data and to find individual instances. 分析 是一个强大的工具,既可用于了解性能和使用情况,也可用于诊断。Analytics is a powerful tool for both for understanding performance and usage, and for diagnostic purposes.

分析示例

7.在服务器上安装应用7. Install your app on the server

现在,将应用程序发布到服务器供用户使用,然后查看门户上显示的遥测数据。Now publish your app to the server, let people use it, and watch the telemetry show up on the portal.

  • 请确保防火墙允许应用程序将遥测数据发送到以下端口:Make sure your firewall allows your application to send telemetry to these ports:

    • dc.services.visualstudio.com:443dc.services.visualstudio.com:443
    • f5.services.visualstudio.com:443f5.services.visualstudio.com:443
  • 如果必须通过防火墙路由传出流量,需定义系统属性 http.proxyHosthttp.proxyPortIf outgoing traffic must be routed through a firewall, define system properties http.proxyHost and http.proxyPort.

  • 在 Windows 服务器上,安装:On Windows servers, install:

Azure 应用服务配置 (Spring Boot)Azure App Service config (Spring Boot)

在 Windows 上运行的 Spring Boot 应用需要额外的配置才能在 Azure 应用服务上运行。Spring Boot apps running on Windows require additional configuration to run on Azure App Services. 修改 web.config 并添加以下项:Modify web.config and add the following:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
        </handlers>
        <httpPlatform processPath="%JAVA_HOME%\bin\java.exe" arguments="-Djava.net.preferIPv4Stack=true -Dserver.port=%HTTP_PLATFORM_PORT% -jar &quot;%HOME%\site\wwwroot\AzureWebAppExample-0.0.1-SNAPSHOT.jar&quot;">
        </httpPlatform>
    </system.webServer>
</configuration>

异常和请求失败Exceptions and request failures

Application Insights web 筛选器自动收集未经处理的异常和请求失败。Unhandled exceptions and request failures are automatically collected by the Application Insights web filter.

若要收集其他异常的数据, 可以在代码中插入对 trackException () 的调用To collect data on other exceptions, you can insert calls to trackException() in your code.

监视方法调用和外部依赖项Monitor method calls and external dependencies

安装 Java 代理 ,记录指定的内部方法、通过 JDBC 发出的调用以及计时数据。Install the Java Agent to log specified internal methods and calls made through JDBC, with timing data.

对于自动操作命名, 则为。And for automatic operation naming.

W3C 分布式跟踪W3C distributed tracing

Application Insights Java SDK 现支持 W3C 分布式跟踪The Application Insights Java SDK now supports W3C distributed tracing.

有关关联的文章中进一步解释了传入的 SDK 配置。The incoming SDK configuration is explained further in our article on correlation.

AI-Agent.xml 文件中定义了传出 SDK 配置。Outgoing SDK configuration is defined in the AI-Agent.xml file.

性能计数器Performance counters

打开“调查”、“指标”,查看一系列性能计数器。Open Investigate, Metrics, to see a range of performance counters.

已选中进程专用字节的指标窗格的屏幕截图

自定义性能计数器收集Customize performance counter collection

要禁用收集性能计数器的标准集,请将以下代码添加到 ApplicationInsights.xml 文件的根节点下:To disable collection of the standard set of performance counters, add the following code under the root node of the ApplicationInsights.xml file:

    <PerformanceCounters>
       <UseBuiltIn>False</UseBuiltIn>
    </PerformanceCounters>

收集其他性能计数器Collect additional performance counters

可以指定要收集的其他性能计数器。You can specify additional performance counters to be collected.

JMX 计数器(由 Java 虚拟机公开)JMX counters (exposed by the Java Virtual Machine)

    <PerformanceCounters>
      <Jmx>
        <Add objectName="java.lang:type=ClassLoading" attribute="TotalLoadedClassCount" displayName="Loaded Class Count"/>
        <Add objectName="java.lang:type=Memory" attribute="HeapMemoryUsage.used" displayName="Heap Memory Usage-used" type="composite"/>
      </Jmx>
    </PerformanceCounters>
  • displayName – Application Insights 门户中显示的名称。displayName – The name displayed in the Application Insights portal.
  • objectName – JMX 对象名称。objectName – The JMX object name.
  • attribute – 提取的 JMX 对象名称属性attribute – The attribute of the JMX object name to fetch
  • type (可选)- JMX 对象的属性类型:type (optional) - The type of JMX object’s attribute:
    • 默认值:简单类型,例如 int 或 long。Default: a simple type such as int or long.
    • composite:性能计数器数据采用“Attribute.Data”格式composite: the perf counter data is in the format of 'Attribute.Data'
    • tabular:性能计数器数据采用表行格式tabular: the perf counter data is in the format of a table row

Windows 性能计数器Windows performance counters

每个 Windows 性能计数器 是类别的成员(就好比字段是类的成员)。Each Windows performance counter is a member of a category (in the same way that a field is a member of a class). 类别可以是全局的,也可以是带编号的实例或命名实例。Categories can either be global, or can have numbered or named instances.

    <PerformanceCounters>
      <Windows>
        <Add displayName="Process User Time" categoryName="Process" counterName="%User Time" instanceName="__SELF__" />
        <Add displayName="Bytes Printed per Second" categoryName="Print Queue" counterName="Bytes Printed/sec" instanceName="Fax" />
      </Windows>
    </PerformanceCounters>
  • displayName – Application Insights 门户中显示的名称。displayName – The name displayed in the Application Insights portal.
  • categoryName – 与此性能计数器关联的性能计数器类别(性能对象)。categoryName – The performance counter category (performance object) with which this performance counter is associated.
  • counterName – 性能计数器的名称。counterName – The name of the performance counter.
  • instanceName – 性能计数器类别实例的名称,如果类别包含单个实例,则为空字符串 ("")。instanceName – The name of the performance counter category instance, or an empty string (""), if the category contains a single instance. 如果 categoryName 为 Process,而要收集的性能计数器来自应用运行所在的当前 JVM 进程,请指定 "__SELF__"If the categoryName is Process, and the performance counter you'd like to collect is from the current JVM process on which your app is running, specify "__SELF__".

Unix 性能计数器Unix performance counters

获取用户和会话数据Get user and session data

好了,现在正在从 Web 服务发送遥测数据。OK, you're sending telemetry from your web server. 若要获取应用程序的 360 度全方位视图,可以添加更多监视:Now to get the full 360-degree view of your application, you can add more monitoring:

发送自己的遥测数据Send your own telemetry

安装 SDK 后,可以使用 API 发送自己的遥测数据。Now that you've installed the SDK, you can use the API to send your own telemetry.

可用性 Web 测试Availability web tests

Application Insights 可以定期测试网站,检查网站是否正常运行且做出响应。Application Insights can test your website at regular intervals to check that it's up and responding well.

详细了解如何设置可用性 web 测试。Learn more about how to set up availability web tests.

有疑问?Questions? 遇到问题?Problems?

Java 故障排除Troubleshooting Java

后续步骤Next steps