在 Application Insights 中分析 Azure Functions 遥测数据Analyze Azure Functions telemetry in Application Insights

Azure Functions 与 Application Insights 集成,以用于更好地监视函数应用。Azure Functions integrates with Application Insights to better enable you to monitor your function apps. Application Insights 收集函数应用生成的遥测数据,包括应用写入到日志的信息。Application Insights collects telemetry data generated by your function app, including information your app writes to logs. 通常,在创建函数应用时会启用 Application Insights 集成。Application Insights integration is typically enabled when your function app is created. 如果函数应用未设置检测密钥,则必须先启用 Application Insights 集成If your function app doesn't have the instrumentation key set, you must first enable Application Insights integration.

默认情况下,从函数应用中收集的数据会存储在 Application Insights 中。By default, the data collected from your function app is stored in Application Insights. Azure 门户中,Application Insights 提供了一组全面的遥测数据可视化效果。In the Azure portal, Application Insights provides an extensive set of visualizations of your telemetry data. 你可以深入查看错误日志,并且可以查询事件和指标。You can drill into error logs and query events and metrics. 本文提供了一些基本示例来说明如何查看和查询收集的数据。This article provides basic examples of how to view and query your collected data. 若要详细了解如何在 Application Insights 中探索函数应用数据,请参阅什么是 Application Insights?To learn more about exploring your function app data in Application Insights, see What is Application Insights?.

若要详细了解数据保留和可能产生的存储成本,请参阅 Application Insights 中的数据收集、保留和存储To learn more about data retention and potential storage costs, see Data collection, retention, and storage in Application Insights.

在“监视”选项卡中查看遥测数据Viewing telemetry in Monitor tab

启用 Application Insights 集成后,可以在“监视”选项卡中查看遥测数据。With Application Insights integration enabled, you can view telemetry data in the Monitor tab.

  1. 在函数应用页中,选择在配置 Application Insights 之后至少运行过一次的函数。In the function app page, select a function that has run at least once after Application Insights was configured. 然后,在左窗格中选择“监视”。Then, select Monitor from the left pane. 定期选择“刷新”,直到显示函数调用列表。Select Refresh periodically, until the list of function invocations appears.

    调用列表

    备注

    在遥测客户端对数据进行批处理以传输到服务器时,最长可能需要 5 分钟的时间才会显示该列表。It can take up to five minutes for the list to appear while the telemetry client batches data for transmission to the server. 这种延迟不适用于实时指标流The delay doesn't apply to the Live Metrics Stream. 加载页面时,该服务会连接到 Functions 主机,因此,日志会直接流式传输到页面。That service connects to the Functions host when you load the page, so logs are streamed directly to the page.

  2. 若要查看特定函数调用的日志,选择该调用对应的“日期 (UTC)”列链接。To see the logs for a particular function invocation, select the Date (UTC) column link for that invocation. 该调用的日志记录输出显示在新页中。The logging output for that invocation appears in a new page.

    调用详细信息

  3. 选择“在 Application Insights 中运行”,以查看在 Azure 日志中检索 Azure Monitor 日志数据的查询源。Choose Run in Application Insights to view the source of the query that retrieves the Azure Monitor log data in Azure Log. 如果这是首次在订阅中使用 Azure Log Analytics,系统会要求启用它。If this is your first time using Azure Log Analytics in your subscription, you're asked to enable it.

  4. 启用 Log Analytics 后,将显示以下查询。After you enable Log Analytics, the following query is displayed. 可以看到,查询结果仅限于最近 30 天 (where timestamp > ago(30d)),而且显示的结果不超过 20 行 (take 20)。You can see that the query results are limited to the last 30 days (where timestamp > ago(30d)), and the results show no more than 20 rows (take 20). 相比之下,函数的调用详细信息列表显示最近 30 天的信息,没有任何限制。In contrast, the invocation details list for your function is for the last 30 days with no limit.

    Application Insights Analytics 调用列表

有关详细信息,请参阅本文稍后的查询遥测数据For more information, see Query telemetry data later in this article.

在 Application Insights 中查看遥测View telemetry in Application Insights

若要在 Azure 门户中从某个函数应用打开 Application Insights,请执行以下操作:To open Application Insights from a function app in the Azure portal:

  1. 在门户中浏览到你的函数应用。Browse to your function app in the portal.

  2. 在左侧页面中,选择“设置”下方的“Application Insights” 。Select Application Insights under Settings in the left page.

  3. 如果这是你首次通过自己的订阅使用 Application Insights,系统将会提示你启用它。If this is your first time using Application Insights with your subscription, you'll be prompted to enable it. 为此,请选择“打开 Application Insights”,然后在下一页上选择“应用” 。To do this, select Turn on Application Insights, and then select Apply on the next page.

从函数应用“概述”页面打开 Application Insights

有关如何使用 Application Insights 的信息,请参阅 Application Insights 文档For information about how to use Application Insights, see the Application Insights documentation. 本部分介绍如何在 Application Insights 中查看数据的一些示例。This section shows some examples of how to view data in Application Insights. 如果已经熟悉 Application Insights,则可以直接转到有关如何配置和自定义遥测数据的部分If you're already familiar with Application Insights, you can go directly to the sections about how to configure and customize the telemetry data.

Application Insights“概述”选项卡

在评估函数中的行为、性能和错误时,Application Insights 的以下方面可能会有所帮助:The following areas of Application Insights can be helpful when evaluating the behavior, performance, and errors in your functions:

调查Investigate 说明Description
失败Failures 基于函数失败和服务器异常来创建图表和警报。Create charts and alerts based on function failures and server exceptions. 操作名称是函数名称。The Operation Name is the function name. 不显示依赖项中的失败,除非为依赖项实现了自定义遥测。Failures in dependencies aren't shown unless you implement custom telemetry for dependencies.
性能Performance 通过查看每个 Cloud 角色实例的资源利用率和吞吐量来分析性能问题。Analyze performance issues by viewing resource utilization and throughput per Cloud role instances. 如果要针对函数阻碍基础资源正常工作的情况进行调试,此性能数据会很有用。This performance data can be useful for debugging scenarios where functions are bogging down your underlying resources.
指标Metrics 创建基于指标的图表和警报。Create charts and alerts that are based on metrics. 指标包括函数调用次数、执行时间和成功率。Metrics include the number of function invocations, execution time, and success rates.
实时指标:Live Metrics 随着指标数据的创建,近实时地查看指标数据。View metrics data as it's created in near real time.

查询遥测数据Query telemetry data

借助 Application Insights Analytics,便可以访问数据库中以表形式存储的所有遥测数据。Application Insights Analytics gives you access to all telemetry data in the form of tables in a database. Analytics 提供了一种用于提取、处理和可视化数据的查询语言。Analytics provides a query language for extracting, manipulating, and visualizing the data.

选择“日志”以浏览或查询记录的事件。Choose Logs to explore or query for logged events.

Analytics 示例

下面是一个查询示例,它显示过去 30 分钟内每个辅助角色的请求的分布。Here's a query example that shows the distribution of requests per worker over the last 30 minutes.

requests
| where timestamp > ago(30m) 
| summarize count() by cloud_RoleInstance, bin(timestamp, 1m)
| render timechart

可用的表会显示在左侧的“架构”选项卡中。The tables that are available are shown in the Schema tab on the left. 可以在下表中找到由函数调用生成的数据:You can find data generated by function invocations in the following tables:

Table 说明Description
tracestraces 由函数代码中的运行时、规模控制器和跟踪创建的日志。Logs created by the runtime, scale controller, and traces from your function code.
requestsrequests 一个请求用于一个函数调用。One request for each function invocation.
异常exceptions 由运行时引发的任何异常。Any exceptions thrown by the runtime.
customMetricscustomMetrics 成功和失败调用的计数、成功率和持续时间。The count of successful and failing invocations, success rate, and duration.
customEventscustomEvents 运行时跟踪的事件,例如:触发函数的 HTTP 请求。Events tracked by the runtime, for example: HTTP requests that trigger a function.
performanceCountersperformanceCounters 有关运行函数的服务器的性能的信息。Information about the performance of the servers that the functions are running on.

其他表适用于可用性测试、客户端和浏览器遥测。The other tables are for availability tests, and client and browser telemetry. 可以实现自定义遥测以向其中添加数据。You can implement custom telemetry to add data to them.

在每个表内,一些函数特定的数据位于 customDimensions 字段。Within each table, some of the Functions-specific data is in a customDimensions field. 例如,以下查询检索所有具有日志级别 Error 的跟踪。For example, the following query retrieves all traces that have log level Error.

traces 
| where customDimensions.LogLevel == "Error"

运行时提供了 customDimensions.LogLevelcustomDimensions.Category 字段。The runtime provides the customDimensions.LogLevel and customDimensions.Category fields. 可以在日志中提供在函数代码中编写的其他字段。You can provide additional fields in logs that you write in your function code. 有关用 C# 编写的示例,请参阅 .NET 类库开发人员指南中的结构化日志记录For an example in C#, see Structured logging in the .NET class library developer guide.

查询规模控制器日志Query scale controller logs

此功能为预览版。This feature is in preview.

启用规模控制器日志 Application Insights 集成后,可以使用 Application Insights 日志搜索来查询已发出的规模控制器日志。After enabling both scale controller logging and Application Insights integration, you can use the Application Insights log search to query for the emitted scale controller logs. 规模控制器日志保存在 ScaleControllerLogs 下的 traces 集合中。Scale controller logs are saved in the traces collection under the ScaleControllerLogs category.

以下查询可用于在指定时间段内搜索当前函数应用的所有规模控制器日志:The following query can be used to search for all scale controller logs for the current function app within the specified time period:

traces 
| extend CustomDimensions = todynamic(tostring(customDimensions))
| where CustomDimensions.Category == "ScaleControllerLogs"

以下查询对上一个查询进行了扩展,以显示如何只获取指示规模更改的日志:The following query expands on the previous query to show how to get only logs indicating a change in scale:

traces 
| extend CustomDimensions = todynamic(tostring(customDimensions))
| where CustomDimensions.Category == "ScaleControllerLogs"
| where message == "Instance count changed"
| extend Reason = CustomDimensions.Reason
| extend PreviousInstanceCount = CustomDimensions.PreviousInstanceCount
| extend NewInstanceCount = CustomDimensions.CurrentInstanceCount

特定于消耗计划的指标Consumption plan-specific metrics

消耗计划中运行时,单个函数执行的执行成本以“GB 秒”来度量 。When running in a Consumption plan, the execution cost of a single function execution is measured in GB-seconds. 执行成本是通过将其内存用量与执行时间相结合计算得出的。Execution cost is calculated by combining its memory usage with its execution time. 若要了解详细信息,请参阅估算消耗计划成本To learn more, see Estimating Consumption plan costs.

以下遥测数据查询特定于对在消耗计划中运行函数的成本有影响的指标。The following telemetry queries are specific to metrics that impact the cost of running functions in the Consumption plan.

确定内存用量Determine memory usage

在“监视”下选择“日志(分析)”,复制以下遥测查询并将其粘贴到查询窗口中,然后选择“运行”。 Under Monitoring , select Logs (Analytics) , then copy the following telemetry query and paste it into the query window and select Run . 此查询返回每个采样时间的总内存用量。This query returns the total memory usage at each sampled time.

performanceCounters
| where name == "Private Bytes"
| project timestamp, name, value

结果类似于以下示例:The results look like the following example:

时间戳 [UTC]timestamp [UTC] namename value
9/12/2019, 1:05:14.947 AM9/12/2019, 1:05:14.947 AM 专用字节数Private Bytes 209,932,288209,932,288
9/12/2019, 1:06:14.994 AM9/12/2019, 1:06:14.994 AM 专用字节数Private Bytes 212,189,184212,189,184
9/12/2019, 1:06:30.010 AM9/12/2019, 1:06:30.010 AM 专用字节数Private Bytes 231,714,816231,714,816
9/12/2019, 1:07:15.040 AM9/12/2019, 1:07:15.040 AM 专用字节数Private Bytes 210,591,744210,591,744
9/12/2019, 1:12:16.285 AM9/12/2019, 1:12:16.285 AM 专用字节数Private Bytes 216,285,184216,285,184
9/12/2019, 1:12:31.376 AM9/12/2019, 1:12:31.376 AM 专用字节数Private Bytes 235,806,720235,806,720

确定持续时间Determine duration

Azure Monitor 可跟踪资源级指标,对于函数来说,就是跟踪函数应用指标。Azure Monitor tracks metrics at the resource level, which for Functions is the function app. Application Insights 集成会发出每个函数的指标。Application Insights integration emits metrics on a per-function basis. 下面是一个示例分析查询,可用于获取函数的平均持续时间:Here's an example analytics query to get the average duration of a function:

customMetrics
| where name contains "Duration"
| extend averageDuration = valueSum / valueCount
| summarize averageDurationMilliseconds=avg(averageDuration) by name
namename averageDurationMillisecondsaverageDurationMilliseconds
QueueTrigger AvgDurationMsQueueTrigger AvgDurationMs 16.08716.087
QueueTrigger MaxDurationMsQueueTrigger MaxDurationMs 90.24990.249
QueueTrigger MinDurationMsQueueTrigger MinDurationMs 8.5228.522

Azure Monitor 指标Azure Monitor metrics

除了 Application Insights 收集的遥测数据外,还可以从 Azure Monitor 指标获取有关函数应用运行方式的数据。In addition to telemetry data collected by Application Insights, you can also get data about how the function app is running from Azure Monitor Metrics. 除了通常可用于 App 服务应用的指标外,还有两个特定于相关函数的指标:Along with the usual metrics available to App Service apps, there are two metrics specific to Functions that are of interest:

指标Metric 说明Description
FunctionExecutionCountFunctionExecutionCount 函数执行计数表示函数应用已执行的次数。Function execution count indicates the number of times your function app has executed. 这与函数在应用中运行的次数相关。This correlates to the number of times a function runs in your app. 此指标目前不支持在 Linux 上运行的高级和专用(App 服务)计划。This metric isn't currently supported for Premium and Dedicated (App Service) plans running on Linux.
FunctionExecutionUnitsFunctionExecutionUnits 函数执行单位由执行次数和内存使用组成。Function execution units are a combination of execution time and your memory usage. 目前无法通过 Azure Monitor 获取内存数据这一指标。Memory data isn't a metric currently available through Azure Monitor. 但是,如果要优化应用的内存用量,可以使用 Application Insights 收集的性能计数器数据。However, if you want to optimize the memory usage of your app, can use the performance counter data collected by Application Insights. 此指标目前不支持在 Linux 上运行的高级和专用(App 服务)计划。This metric isn't currently supported for Premium and Dedicated (App Service) plans running on Linux.

若要详细了解如何使用 Application Insights 数据计算消耗计划的成本,请参阅估计消耗计划成本To learn more about calculating costs for a Consumption plan using Application Insights data, see Estimating Consumption plan costs. 若要详细了解如何使用监视器资源管理器查看指标,请参阅 Azure 指标资源管理器入门To learn more about using Monitor Explorer to view metrics, see Getting started with Azure Metrics Explorer.

后续步骤Next steps

请参阅以下文章,以详细了解如何监视 Azure Functions:Learn more about monitoring Azure Functions: