如何为 Azure Functions 配置监视How to configure monitoring for Azure Functions

Azure Functions 与 Application Insights 集成,从而使你能够更好地监视函数应用。Azure Functions integrates with Application Insights to better enable you to monitor your function apps. Application Insights(Azure Monitor 的一项功能)是一种可扩展的应用程序性能管理 (APM) 服务,该服务收集函数应用生成的数据,包括应用写入日志的信息。Application Insights, a feature of Azure Monitor, is an extensible Application Performance Management (APM) service that collects 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 app doesn't have the instrumentation key set, you must first enable Application Insights integration.

可以使用 Application Insights 而无需任何自定义配置。You can use Application Insights without any custom configuration. 默认配置可能会产生大量数据。The default configuration can result in high volumes of data. 如果使用的是 Visual Studio Azure 订阅,可能会达到 Application Insights 的数据上限。If you're using a Visual Studio Azure subscription, you might hit your data cap for Application Insights. 若要详细了解 Application Insights 成本,请参阅管理 Application Insights 的使用情况和成本To learn more about Application Insights costs, see Manage usage and costs for Application Insights.

本文后面的部分将介绍如何配置和自定义函数发送到 Application Insights 的数据。Later in this article, you learn how to configure and customize the data that your functions send to Application Insights. 对于函数应用,在 host.json 文件中配置日志记录。For a function app, logging is configured in the host.json file.

备注

可以使用专门配置的应用程序设置来表示针对特定环境的 host.json 文件中的特定设置。You can use specially configured application settings to represent specific settings in a host.json file for a specific environment. 这使你可以有效地更改 host.json 设置,而不必在项目中重新发布 host.json 文件。This lets you effectively change host.json settings without having to republish the host.json file in your project. 若要了解详细信息,请参阅替代 host.json 值To learn more, see Override host.json values.

配置类别Configure categories

对于每个日志,Azure Functions 记录器都包含一个类别。The Azure Functions logger includes a category for every log. 类别指示运行时代码或函数代码的哪个部分编写日志。The category indicates which part of the runtime code or your function code wrote the log. 版本 1.x 和更高版本中的类别有所不同。Categories differ between version 1.x and later versions. 下表描述了运行时创建的日志的主要类别。The following chart describes the main categories of logs that the runtime creates.

类别Category Table 说明Description
Function.<YOUR_FUNCTION_NAME> 依赖项dependencies 系统会自动收集一些服务的依赖项数据。Dependency data is automatically collected for some services. 对于成功运行,这些日志处于 Information 级别。For successful runs, these logs are at the Information level. 若要了解详细信息,请参阅依赖项To learn more, see Dependencies. 异常记录在 Error 级别。Exceptions are logged at the Error level. 运行时还会创建 Warning 级别日志,例如将队列消息发送到病毒队列时。The runtime also creates Warning level logs, such as when queue messages are sent to the poison queue.
Function.<YOUR_FUNCTION_NAME> customMetricscustomMetrics
customEventscustomEvents
使用 C# 和 JavaScript SDK,可以收集自定义指标并记录自定义事件。C# and JavaScript SDKs let you collect custom metrics and log custom events. 若要了解详细信息,请参阅自定义遥测数据To learn more, see Custom telemetry data.
Function.<YOUR_FUNCTION_NAME> tracestraces 包括针对特定函数运行的函数已启动和已完成日志。Includes function started and completed logs for specific function runs. 对于成功运行,这些日志处于 Information 级别。For successful runs, these logs are at the Information level. 异常记录在 Error 级别。Exceptions are logged at the Error level. 运行时还会创建 Warning 级别日志,例如将队列消息发送到病毒队列时。The runtime also creates Warning level logs, such as when queue messages are sent to the poison queue.
Function.<YOUR_FUNCTION_NAME>.User tracestraces 用户生成的日志,可以是任何日志级别。User-generated logs, which can be any log level. 若要详细了解如何从函数写入日志,请参阅写入日志To learn more about writing to logs from your functions, see Writing to logs.
Host.Aggregator customMetricscustomMetrics 这些运行时生成的日志在一段可配置的时间内提供函数调用的计数和平均值。These runtime-generated logs provide counts and averages of function invocations over a configurable period of time. 默认时段为 30 秒或 1,000 个结果,以先满足的条件为准。The default period is 30 seconds or 1,000 results, whichever comes first. 示例包括运行数、成功率和持续时间。Examples are the number of runs, success rate, and duration. 所有这些日志均在 Information 级别编写。All of these logs are written at Information level. 如果在 Warning 或更高级别进行筛选,则不会看到任何这些数据。If you filter at Warning or above, you won't see any of this data.
Host.Results requestsrequests 这些运行时生成的日志指示函数是成功还是失败。These runtime-generated logs indicate success or failure of a function. 所有这些日志均在 Information 级别编写。All of these logs are written at Information level. 如果在 Warning 或更高级别进行筛选,则不会看到任何这些数据。If you filter at Warning or above, you won't see any of this data.
Microsoft tracestraces 反映主机调用的 .NET 运行时组件的完全限定的日志类别。Fully-qualified log category that reflects a .NET runtime component invoked by the host.
Worker tracestraces 语言工作进程为非 .NET 语言生成的日志。Logs generated by the language worker process for non-.NET languages. 语言工作日志也可以记录在 Microsoft.* 类别中,例如 Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcFunctionInvocationDispatcherLanguage worker logs may also be logged in a Microsoft.* category, such as Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcFunctionInvocationDispatcher. 这些日志在 Information 级别写入。These logs are written at Information level.

备注

对于 .NET 类库函数,这些类别假定你使用的是 ILogger 而不是 ILogger<T>For .NET class library functions, these categories assume you are using ILogger and not ILogger<T>. 若要了解详细信息,请参阅 Functions ILogger 文档To learn more, see the Functions ILogger documentation.

表列指示将日志写入 Application Insights 中的哪个表。The Table column indicates to which table in Application Insights the log is written.

配置日志级别Configure log levels

为每个日志分配日志级别。A log level is assigned to every log. 该值是表示相对重要性的整数:The value is an integer that indicates relative importance:

LogLevelLogLevel 代码Code 说明Description
跟踪Trace 00 包含最详细消息的日志。Logs that contain the most detailed messages. 这些消息可能包含敏感应用程序数据。These messages may contain sensitive application data. 这些消息默认情况下处于禁用状态,并且绝不应在生产环境中启用。These messages are disabled by default and should never be enabled in a production environment.
调试Debug 11 在开发过程中用于交互式调查的日志。Logs that are used for interactive investigation during development. 这些日志应主要包含对调试有用的信息,并且没有长期价值。These logs should primarily contain information useful for debugging and have no long-term value.
信息Information 22 跟踪应用程序的常规流的日志。Logs that track the general flow of the application. 这些日志应具有长期价值。These logs should have long-term value.
警告Warning 33 突出显示应用程序流中的异常或意外事件,但不会导致应用程序执行停止的日志。Logs that highlight an abnormal or unexpected event in the application flow, but don't otherwise cause the application execution to stop.
错误Error 44 当前执行流因失败而停止时突出显示的日志。Logs that highlight when the current flow of execution is stopped because of a failure. 这些错误应指示当前活动中的故障,而不是应用程序范围内的故障。These errors should indicate a failure in the current activity, not an application-wide failure.
严重Critical 55 描述不可恢复的应用程序/系统崩溃或需要立即引起注意的灾难性故障的日志。Logs that describe an unrecoverable application or system crash, or a catastrophic failure that requires immediate attention.
None 66 禁用指定类别的日志记录。Disables logging for the specified category.

Host.json 文件配置确定函数应用发送到 Application Insights 的日志记录数量。The host.json file configuration determines how much logging a functions app sends to Application Insights.

对于每个类别,均可以指示要发送的最小日志级别。For each category, you indicate the minimum log level to send. host.json 设置因 Functions 运行时版本而异。The host.json settings vary depending on the Functions runtime version.

下面的示例根据以下规则定义日志记录:The example below defines logging based on the following rules:

  • 对于 Host.ResultsFunction 的日志,仅记录 Error 或更高级别的事件。For logs of Host.Results or Function, only log events at Error or a higher level.
  • 对于 Host.Aggregator 的日志,记录所有生成的指标 (Trace)。For logs of Host.Aggregator, log all generated metrics (Trace).
  • 对于所有其他日志(包括用户日志),仅记录 Information 级别及更高级别的事件。For all other logs, including user logs, log only Information level and higher events.
{
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Information",
      "Host.Results": "Error",
      "Function": "Error",
      "Host.Aggregator": "Trace"
    }
  }
}

如果 host.json 包含以相同字符串开头的多个日志,则首先匹配定义更多的日志。If host.json includes multiple logs that start with the same string, the more defined logs ones are matched first. 考虑以下示例,该示例在运行时中记录 Error 级别上除 Host.Aggregator 之外的所有内容:Consider the following example that logs everything in the runtime, except Host.Aggregator, at the Error level:

{
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Information",
      "Host": "Error",
      "Function": "Error",
      "Host.Aggregator": "Information"
    }
  }
}

可以使用日志级别设置 None 来阻止为某个类别写入任何日志。You can use a log level setting of None prevent any logs from being written for a category.

配置聚合器Configure the aggregator

如前一部分中所述,运行时聚合一段时间内有关函数执行的数据。As noted in the previous section, the runtime aggregates data about function executions over a period of time. 默认时段为 30 秒或 1,000 次运行,以先满足的条件为准。The default period is 30 seconds or 1,000 runs, whichever comes first. 可以在 host.json 文件中配置此设置。You can configure this setting in the host.json file. 下面是一个示例:Here's an example:

{
    "aggregator": {
      "batchSize": 1000,
      "flushTimeout": "00:00:30"
    }
}

配置采样Configure sampling

Application Insights 具有采样功能,可以防止在峰值负载时为已完成的执行生成过多的遥测数据。Application Insights has a sampling feature that can protect you from producing too much telemetry data on completed executions at times of peak load. 当传入执行的速率超过指定的阈值时,Application Insights 开始随机忽略某些传入执行。When the rate of incoming executions exceeds a specified threshold, Application Insights starts to randomly ignore some of the incoming executions. 每秒执行的最大次数的默认设置为 20(版本 1.x 中为 5)。The default setting for maximum number of executions per second is 20 (five in version 1.x). 可以在 host.json 中配置采样。You can configure sampling in host.json. 下面是一个示例:Here's an example:

{
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "maxTelemetryItemsPerSecond" : 20,
        "excludedTypes": "Request;Exception"
      }
    }
  }
}

可以从采样中排除某些类型的遥测。You can exclude certain types of telemetry from sampling. 在此示例中,采样中排除了类型为 RequestException 的数据。In this example, data of type Request and Exception is excluded from sampling. 这可确保记录所有函数执行(请求)和异常,而其他类型的遥测仍会受到采样的限制。This makes sure that all function executions (requests) and exceptions are logged while other types of telemetry remain subject to sampling.

若要了解详细信息,请参阅 Application Insights 中的采样To learn more, see Sampling in Application Insights.

配置缩放控制器日志Configure scale controller logs

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

可以让 Azure Functions 缩放控制器将日志发出到 Application Insights 或 Blob 存储,以便更好地了解缩放控制器为函数应用做出的决策。You can have the Azure Functions scale controller emit logs to either Application Insights or to Blob storage to better understand the decisions the scale controller is making for your function app.

若要启用此功能,请将名为 SCALE_CONTROLLER_LOGGING_ENABLED 的应用程序设置添加到函数应用设置中。To enable this feature, you add an application setting named SCALE_CONTROLLER_LOGGING_ENABLED to your function app settings. 此设置的值必须采用基于以下规范的 <DESTINATION>:<VERBOSITY> 格式:The value of this setting must be of the format <DESTINATION>:<VERBOSITY>, based on the following:

<DESTINATION> 日志发送到的目标。The destination to which logs are sent. 有效值为 AppInsightsBlobValid values are AppInsights and Blob.
使用 AppInsights 时,请确保在函数应用中启用 Application InsightsWhen you use AppInsights, make sure Application Insights is enabled in your function app.
将目标设置为 Blob 时,将在名为 azure-functions-scale-controller 的 blob 容器中创建日志,该容器位于 AzureWebJobsStorage 应用程序设置中设置的默认存储帐户中。When you set the destination to Blob, logs are created in a blob container named azure-functions-scale-controller in the default storage account set in the AzureWebJobsStorage application setting.
<VERBOSITY> 指定日志记录级别。Specifies the level of logging. 支持的值为 NoneWarningVerboseSupported values are None, Warning, and Verbose.
设置为 Verbose 时,缩放控制器将记录辅助角色计数每次更改的原因,以及有关将这些因素纳入决策的触发器的信息。When set to Verbose, the scale controller logs a reason for every change in the worker count, as well as information about the triggers that factor into those decisions. 详细日志包含触发器警告和缩放控制器运行前后触发器使用的哈希。Verbose logs include trigger warnings and the hashes used by the triggers before and after the scale controller runs.

提示

请记住,将“缩放控制器日志记录”保留为启用时,它会影响监视函数应用的潜在成本Keep in mind that while you leave scale controller logging enabled, it impacts the potential costs of monitoring your function app. 请考虑启用日志记录,直到收集到的数据足以了解缩放控制器的行为方式,然后将其禁用。Consider enabling logging until you have collected enough data to understand how the scale controller is behaving, and then disabling it.

例如,以下 Azure CLI 命令会启用从缩放控制器到 Application Insights 的详细日志记录:For example, the following Azure CLI command turns on verbose logging from the scale controller to Application Insights:

az functionapp config appsettings set --name <FUNCTION_APP_NAME> \
--resource-group <RESOURCE_GROUP_NAME> \
--settings SCALE_CONTROLLER_LOGGING_ENABLED=AppInsights:Verbose

在此示例中,请将 <FUNCTION_APP_NAME><RESOURCE_GROUP_NAME> 分别替换为函数应用名称和资源组名称。In this example, replace <FUNCTION_APP_NAME> and <RESOURCE_GROUP_NAME> with the name of your function app and the resource group name, respectively.

以下 Azure CLI 命令通过将详细程度设置为 None 来禁用日志记录:The following Azure CLI command disables logging by setting the verbosity to None:

az functionapp config appsettings set --name <FUNCTION_APP_NAME> \
--resource-group <RESOURCE_GROUP_NAME> \
--settings SCALE_CONTROLLER_LOGGING_ENABLED=AppInsights:None

还可以通过使用以下 Azure CLI 命令删除 SCALE_CONTROLLER_LOGGING_ENABLED 设置来禁用日志记录:You can also disable logging by removing the SCALE_CONTROLLER_LOGGING_ENABLED setting using the following Azure CLI command:

az functionapp config appsettings delete --name <FUNCTION_APP_NAME> \
--resource-group <RESOURCE_GROUP_NAME> \
--setting-names SCALE_CONTROLLER_LOGGING_ENABLED

启用 Application Insights 集成Enable Application Insights integration

对于将数据发送到 Application Insights 的函数应用,它需要知道 Application Insights 资源的检测密钥。For a function app to send data to Application Insights, it needs to know the instrumentation key of an Application Insights resource. 该密钥必须位于名为 APPINSIGHTS_INSTRUMENTATIONKEY 的应用设置中。The key must be in an app setting named APPINSIGHTS_INSTRUMENTATIONKEY.

在 Azure 门户中创建函数应用时,请在命令行中使用 Azure Functions Core ToolsVisual Studio Code,默认情况下会启用 Application Insights 集成。When you create your function app in the Azure portal, from the command line by using Azure Functions Core Tools, or by using Visual Studio Code, Application Insights integration is enabled by default. Application Insights 资源的名称与函数应用的相同,并且在同一区域或最接近的区域中创建。The Application Insights resource has the same name as your function app, and it's created either in the same region or in the nearest region.

添加到现有函数应用Add to an existing function app

如果未使用函数应用创建 Application Insights 资源,请使用以下步骤创建资源。If an Application Insights resources wasn't created with your function app, use the following steps to create the resource. 然后,可以添加该资源中的检测密钥,作为函数应用中的应用程序设置You can then add the instrumentation key from that resource as an application setting in your function app.

  1. Azure 门户中,搜索并选择“函数应用”,然后选择你的函数应用。In the Azure portal, search for and select function app, and then choose your function app.

  2. 选择窗口顶部的“未配置 Application Insights”横幅。Select the Application Insights is not configured banner at the top of the window. 如果看不到此横幅,则应用可能已启用 Application Insights。If you don't see this banner, then your app might already have Application Insights enabled.

    从门户启用 Application Insights

  3. 展开“更改资源”,使用下表中指定的设置创建 Application Insights 资源。Expand Change your resource and create an Application Insights resource by using the settings specified in the following table.

    设置Setting 建议的值Suggested value 描述Description
    新资源名称New resource name 唯一的应用名称Unique app name 使用与函数应用相同的名称是最方便的,该名称在订阅中必须独一无二。It's easiest to use the same name as your function app, which must be unique in your subscription.
    位置Location 中国北部 2China North 2 尽可能使用函数应用所在的同一区域,或与该区域接近的区域。If possible, use the same region as your function app, or one that's close to that region.

    创建 Application Insights 资源

  4. 选择“应用”。Select Apply.

    Application Insights 资源在与函数应用相同的资源组和订阅中创建。The Application Insights resource is created in the same resource group and subscription as your function app. 创建资源后,关闭 Application Insights 窗口。After the resource is created, close the Application Insights window.

  5. 在函数应用中,选择“设置”下的“配置”,然后选择“应用程序设置”。 In your function app, select Configuration under Settings, and then select Application settings. 如果看到名为 APPINSIGHTS_INSTRUMENTATIONKEY 的设置,则表明已为在 Azure 中运行的函数应用启用 Application Insights 集成。If you see a setting named APPINSIGHTS_INSTRUMENTATIONKEY, Application Insights integration is enabled for your function app running in Azure. 如果出于某种原因,该设置不存在,请使用 Application Insights 检测密钥作为值来添加该设置。If for some reason this setting doesn't exist, add it using your Application Insights instrumentation key as the value.

备注

早期版本的 Functions 使用了内置监视功能,现不再建议使用该功能。Early versions of Functions used built-in monitoring, which is no longer recommended. 为此类函数应用启用 Application Insights 集成时,还必须禁用内置日志记录功能When enabling Application Insights integration for such a function app, you must also disable built-in logging.

禁用内置日志记录Disable built-in logging

启用 Application Insights 时,请禁用使用 Azure 存储的内置日志记录。When you enable Application Insights, disable the built-in logging that uses Azure Storage. 内置日志记录对于使用轻工作负载测试非常有用,但不适合在高负载生产环境中使用。The built-in logging is useful for testing with light workloads, but isn't intended for high-load production use. 对于生产监视,建议使用 Application Insights。For production monitoring, we recommend Application Insights. 如果在生产环境中使用内置日志记录,日志记录可能因 Azure 存储限制而不完整。If built-in logging is used in production, the logging record might be incomplete because of throttling on Azure Storage.

若要禁用内置日志记录,请删除 AzureWebJobsDashboard 应用设置。To disable built-in logging, delete the AzureWebJobsDashboard app setting. 有关如何在 Azure 门户中删除应用设置的信息,请参阅如何管理函数应用的“应用程序设置”部分。For information about how to delete app settings in the Azure portal, see the Application settings section of How to manage a function app. 在删除应用设置之前,请确保同一函数应用中没有任何现有的函数将此设置用于 Azure 存储触发器或绑定。Before you delete the app setting, make sure no existing functions in the same function app use the setting for Azure Storage triggers or bindings.

后续步骤Next steps

若要详细了解监视,请参阅:To learn more about monitoring, see: