练习 - 在门户中添加日志记录并监视 Azure 函数

已完成

在上一单元中,你了解了将 Application Insights 融入到函数应用程序中的一些优势。 你还了解了你的开发人员团队可用的一些其他的日志记录功能。

在项目研究的这一阶段,你使用 Maven 将函数应用程序部署到了 Azure,并在生产中测试了你的函数应用程序。 下一个任务是将跟踪和日志记录功能添加到应用程序。

在此练习中,你将更新你的函数项目配置文件以支持日志流式处理和 Application Insights。 你还将了解如何将自定义跟踪和应用程序见解事件触发器添加到你的项目代码中。

实时流式传输日志

在 Azure 上部署并运行你的函数应用后,你可以使用简单的 Azure CLI 命令对它进行故障排除,以从应用获取实时日志流式处理。

  1. 在 Azure 门户中,在你的 HttpExample 函数的“概述”页上。 使用“复制到剪贴板”图标复制你的“资源组”和“函数应用”的值。

  2. 在 Azure Cloud Shell 窗口中,输入用于流式传输日志的 az webapp log tail -n <functionAppName> -g <resourceGroup> 命令。 将 <functionAppName><resourceGroup> 替换为你在前面的步骤中保存的值。 例如:

    az webapp log tail -n event-reporting-20240125192009873 -g learn-f0af729c-0493-4b45-a5b8-d6b4783b03da
    
    
  3. 你看到的输出应该类似于以下消息。

    2024-01-25T20:44:58  Welcome, you are now connected to log-streaming service. The default timeout is 2 hours. Change the timeout with the App Setting SCM_LOGSTREAM_TIMEOUT (in seconds). 
    2024-01-25T20:45:58  No new trace in the past 1 min(s).
    
  4. 在 Web 浏览器中打开一个新选项卡,粘贴上一练习中完全构造的 URL,从而访问你的函数应用以生成一些日志。

  5. 完成测试后,在 Cloud Shell 中按 Ctrl+C 关闭日志流。

将检测添加到 Application Insights 的 Java 项目

现在,你已为应用程序启用 Application Insights,接下来要在应用程序中启用它。 若要启用应用程序日志记录和 Application Insights,需要修改配置文件,使其包括必要的库和其他依赖项。

需要更新两个配置文件:pom.xml 和 host.json

修改 pom.xml 文件

  1. 使用 Azure Cloud Shell,将目录更改为项目的根目录:

    cd ~/event-reporting
    
  2. 使用 Cloud Shell 的代码编辑器打开 pom.xml 文件:

    code pom.xml
    
  3. 将以下元素添加到独立的 <dependencies> 部分,从而为你的应用程序启用 Application Insights:

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>applicationinsights-web-auto</artifactId>
        <version>2.6.0</version>
    </dependency>
    

    注意

    请确保将 Application Instights 的 <dependency> 添加到独立的 <dependencies> 集合,而不是 <dependencyManagement> 元素中包含的 <dependencies> 集合。

  4. Ctrl+S 保存 pom.xml 文件,然后按 Ctrl+Q 关闭代码编辑器。

修改 host.json 文件

  1. 使用 Cloud Shell 的代码编辑器打开 host.json 文件:

    code host.json
    
  2. 删除现有的 JSON 代码,并将其替换为以下设置:

    {
        "version": "2.0",
        "extensionBundle": {
            "id": "Microsoft.Azure.Functions.ExtensionBundle",
            "version": "[1.*, 2.0.0)"
        },
        "logging": {
            "fileLoggingMode": "always",
            "logLevel": {
                "default": "Information"
            }
        },
        "applicationInsights": {
            "samplingSettings": {
                "isEnabled": true,
                "maxTelemetryItemsPerSecond" : 5
            }
        }
    }
    

    已定义 extensionBundle 的设置,但 loggingapplicationInsights 定义这些功能的不同设置。

  3. Ctrl+S 保存 host.json 文件,然后按 Ctrl+Q 关闭代码编辑器。

将日志记录和 Application Insights 跟踪添加到项目代码

为了使 Application Insights 收集的、在日志文件中出现的数据更加有效,需要将几个数据日志记录命令添加到应用程序代码。

将日志记录添加到 Function.java 文件

若要向函数添加常规的日志记录,可以在应用程序代码中的关键点处添加类似于以下示例的代码,将其中的 [LOG MESSAGE] 字符串替换为希望在应用程序的日志文件中看到的消息。

context.getLogger().info("[LOG MESSAGE]");

请按以下步骤将日志记录添加到应用程序。

  1. 在 Cloud Shell 编辑器中打开应用程序的 Function.java 文件:

    code ~/event-reporting/src/main/java/com/contoso/functions/Function.java
    

    如果检查现有代码,你会注意到这里存在现有的 context.getLogger() 命令,它是 run() 函数定义后的第一个指令。

  2. 找到以下代码部分,它测试空 GET 查询字符串或空 POST 请求:

    if (name == null) {
        return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
    } else {
        return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
    }
    
  3. 修改这部分代码,使其包含两个 context.getLogger() 命令,这两个命令用于将函数状态输出到日志记录系统:

    if (name == null) {
        context.getLogger().info("Execution failure - Incorrect or missing parameter used.");
        return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
    } else {
        context.getLogger().info("Execution success - name parameter = " + name);
        return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
    }
    
  4. Ctrl+S 保存 Function.java 文件,但不要关闭编辑器,在本练习的下一部分中,你将继续向应用程序添加代码

将 Application Insights 跟踪添加到 Function.java 文件

  1. 将以下 import 语句添加到现有导入集中,此语句将导入 Application Insights 遥测库:

    import com.microsoft.applicationinsights.TelemetryClient;
    
  2. 将以下定义添加到应用程序的 Function() 类,此语句会实例化一个 TelemetryClient 对象:

    private TelemetryClient telemetry = new TelemetryClient();
    
  3. 复制每个 context.getLogger() 语句并修改代码,使每个重复项都调用 telemetry.trackEvent() 而不是 context.getLogger()

    . . .
    context.getLogger().info("Java HTTP trigger processed a request.");
    telemetry.trackEvent("Java HTTP trigger processed a request.");
    
    // Parse query parameter
    String query = request.getQueryParameters().get("name");
    String name = request.getBody().orElse(query);
    
    if (name == null) {
        context.getLogger().info("Execution failure - Incorrect or missing parameter used.");
        telemetry.trackEvent("Execution failure - Incorrect or missing parameter used.");
        return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
    } else {
        context.getLogger().info("Execution success - name parameter = " + name);
        telemetry.trackEvent("Execution success - name parameter = " + name);
        return request.createResponseBuilder(HttpStatus.OK).body("Hi, " + name).build();
    }
    . . .
    
  4. Ctrl+S 保存 Function.java 文件,然后按 Ctrl+Q 关闭代码编辑器。

  5. 最后一项任务是生成、打包并重新部署函数应用程序。

    cd ~/event-reporting
    mvn clean package azure-functions:deploy
    

现在,日志记录和 Application Insights 数据收集已添加到你的函数。

使用 Application Insights 监视 Azure 函数

更新后,应用程序现在已经支持通过系统记录器和 Application Insights 实现的精细日志记录。

  1. 若要生成一些示例 HTTP 流量,请复制你在上一练习中用于在 Web 浏览器中测试应用程序的 URL。 将该 URL 与 cURL 配合使用,在 Azure Cloud Shell 中创建循环,例如:

    while :; do curl https://event-reporting-20200102030405006.azurewebsites.net/api/HttpExample?name=Bob; sleep 1; done
    
  2. 使用激活沙盒时所用的同一帐户登录到 Azure 门户

  3. 在左侧菜单中选择“所有资源”。

  4. 从资源列表中选择你的函数,本练习中函数的名称开头为 event-reporting。 例如:event-reporting-20200102030405006。

  5. 查看“日志流式处理”活动:

    1. 在“函数应用”菜单上选择“日志流”。

    2. 打开“App Insights 日志”下拉菜单,然后选择“文件系统日志”。

      Image showing where to find Log Streaming.

    3. 请注意,示例流量会生成一系列日志条目。

      Image showing Log Streaming.

  6. 查看“实时指标”活动:

    1. 选择“文件系统日志”下拉菜单,然后选择“App Insights 日志”。

    2. 选择“在实时指标中打开”。 现在,你可以看到示例流量生成了 Application Insights 和实时指标结果。

      Image showing Application Insights and Live Metrics highlights.

恭喜,你已成功配置 Azure 函数以实现详细的日志记录。

在继续操作之前,请切换回 Cloud Shell,并按 Ctrl + C 关闭命令循环。