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

监视 Azure FunctionsMonitor Azure Functions

Azure Functions提供了与内置集成Azure Application Insights来监视函数。Azure Functions offers built-in integration with Azure Application Insights to monitor functions. 本文介绍如何配置 Azure Functions 将由系统生成日志文件发送到 Application Insights。This article shows you how to configure Azure Functions to send system-generated log files to Application Insights.

我们建议使用 Application Insights,因为它会收集日志、 性能和数据时出错。We recommend using Application Insights because it collects log, performance, and error data. 它会自动检测性能异常并包括强大的分析工具帮助您诊断问题并了解如何使用你的函数。It automatically detects performance anomalies and includes powerful analytics tools to help you diagnose issues and to understand how your functions are used. Application Insights 有助于持续提高性能与可用性。It's designed to help you continuously improve performance and usability. 您甚至可以在本地函数应用项目开发过程中使用 Application Insights。You can even use Application Insights during local function app project development. 有关详细信息,请参阅什么是 Application Insights?For more information, see What is Application Insights?.

根据所需的 Application Insights 检测内置 Azure Functions,只需要是有效的检测密钥,将函数应用程序连接到 Application Insights 资源。As the required Application Insights instrumentation is built into Azure Functions, all you need is a valid instrumentation key to connect your function app to an Application Insights resource.

Application Insights 定价和限制Application Insights pricing and limits

可以免费试用 Application Insights 与函数应用的集成。You can try out Application Insights integration with Function Apps for free. 没有每日限制可以免费处理多少数据。There's a daily limit to how much data can be processed for free. 可能会达到此限制在测试期间。You might hit this limit during testing. 当你达到每日限制时,Azure 会提供门户和电子邮件通知。Azure provides portal and email notifications when you're approaching your daily limit. 如果您错过这些警报并达到的限制,新的日志不会显示在 Application Insights 查询中。If you miss those alerts and hit the limit, new logs won't appear in Application Insights queries. 请注意以避免不必要的故障排除时间的限制。Be aware of the limit to avoid unnecessary troubleshooting time. 有关详细信息,请参阅在 Application Insights 中管理定价和数据量For more information, see Manage pricing and data volume in Application Insights.

启用 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.

在门户中新的 function appNew function app in the portal

当您Azure 门户中创建 function app,默认情况下启用 Application Insights 的集成。When you create your function app in the Azure portal, Application Insights integration is enabled by default. Application Insights 资源具有相同的名称作为 function app 中,并创建同一区域中或在最近的区域中。The Application Insights resource has the same name as your function app, and it's created either in the same region or in nearest region.

若要查看正在创建的 Application Insights 资源,请选择它以展开Application Insights窗口。To review the Application Insights resource being created, select it to expand the Application Insights window. 您可以更改新的资源名称或选择其他位置Azure 地理位置你想要将数据存储。You can change the New resource name or choose a different Location in an Azure geography where you want to store your data.

在创建函数应用时启用 Application Insights

当你选择创建,Application Insights 资源创建 function app 中,它具有与APPINSIGHTS_INSTRUMENTATIONKEY应用程序设置中设置。When you choose Create, an Application Insights resource is created with your function app, which has the APPINSIGHTS_INSTRUMENTATIONKEY set in application settings. 所有内容就可以了。Everything is ready to go.

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

创建函数应用中使用时Azure CLIVisual Studio,或Visual Studio Code,必须创建 Application Insights 资源。When you create a function app using the Azure CLI, Visual Studio, or Visual Studio Code, you must create the Application Insights resource. 您然后可以检测密钥从该资源为应用程序设置中添加 function app。You can then add the instrumentation key from that resource as an application setting in your function app.

可以通过 Functions 轻松地将 Application Insights 集成从 Azure 门户添加到某个函数应用。Functions makes it simple to add Application Insights integration to a function app from the Azure portal.

  1. 门户中选择“所有服务”>“Function App”,接着选择你的函数应用,然后选择窗口顶部的“Application Insights”横幅 In the portal, select All services > Function Apps, select your function app, and then choose the Application Insights banner at the top of the window

    从门户启用 Application Insights

  2. 创建 Application Insights 资源,方法是使用图像下面表中指定的设置:Create an Application Insights resource by using the settings specified in the table below the image:

    创建 Application Insights 资源

    设置Setting 建议的值Suggested value 说明Description
    名称Name 唯一的应用名称Unique app name 使用与函数应用相同的名称是最方便的,该名称在订阅中必须独一无二。It's easiest to use the same name as your function app, which must be unique in your subscription.
    位置Location 西欧West Europe 尽可能使用与函数应用相同的区域,或与之相近的区域。If possible, use the same region as your function app, or near to it.
  3. 选择“确定”。 Choose OK. Application Insights 资源在与函数应用相同的资源组和订阅中创建。The Application Insights resource is created in the same resource group and subscription as your function app. 创建完以后,请关闭 Application Insights 窗口。After creation completes, close the Application Insights window.

  4. 回到函数应用中,选择“应用程序设置”,然后向下滚动到“应用程序设置”。 Back in your function app, select Application settings, and scroll down to Application settings. 如果看到名为 APPINSIGHTS_INSTRUMENTATIONKEY 的设置,则表明已为在 Azure 中运行的函数应用启用 Application Insights 集成。When you see a setting named APPINSIGHTS_INSTRUMENTATIONKEY, it means that Application Insights integration is enabled for your function app running in Azure.

早期版本的函数使用内置的监视,不再建议。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.

在“监视”选项卡中查看遥测数据View 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 the Monitor tab.

    选择“监视”选项卡

  2. 选择刷新定期,直至函数调用的列表显示。Select Refresh periodically, until the list of function invocations appears.

    它可以需要长达五分钟出现遥测客户端的数据传输到服务器进行批处理的列表。It can take up to five minutes for the list to appear while the telemetry client batches data for transmission to the server. (不适用于延迟实时指标 Stream(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.)

    调用列表

  3. 若要查看特定函数调用的日志,选择该调用对应的“日期”列链接。 To see the logs for a particular function invocation, select the Date column link for that invocation.

    调用详细信息链接

    该调用的日志记录输出显示在新页中。The logging output for that invocation appears in a new page.

    调用详细信息

您可以看到,有两个页面Application Insights 中运行链接到 Application Insights Analytics 查询可检索的数据。You can see that both pages have a Run in Application Insights link to the Application Insights Analytics query that retrieves the data.

在 Application Insights 中运行

将显示下面的查询。The following query is displayed. 您所见,该调用列表将限制到最后一个 30 天。You can see that the invocation list is limited to the last 30 days. 此列表显示不超过 20 个行 (where timestamp > ago(30d) | take 20)。The list shows no more than 20 rows (where timestamp > ago(30d) | take 20). 调用详细信息列表为过去 30 天没有限制。The invocation details list 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,请转到 function app概述页。To open Application Insights from a function app in the Azure portal, go to the function app's Overview page. 配置功能,选择Application InsightsUnder Configured features, select Application Insights.

从函数应用概述页中打开 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:

TabTab 描述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 分析性能问题。Analyze performance issues.
服务器Servers 查看资源利用率和每个服务器的吞吐量。View resource utilization and throughput per server. 在函数阻碍基础资源的调试方案下,此数据非常有用。This data can be useful for debugging scenarios where functions are bogging down your underlying resources. 服务器被称为云角色实例 。Servers are referred to as Cloud role instances.
指标Metrics 创建图表和基于指标的警报。Create charts and alerts that are based on metrics. 度量值包括函数调用、 执行时间和成功率的数。Metrics include the number of function invocations, execution time, and success rates.
实时指标流Live Metrics Stream 创建实时查看指标数据。View metrics data as it's created in real time.

查询遥测数据Query telemetry data

Application Insights 分析,可以访问数据库的表中的窗体中的所有遥测数据。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.

选择 Analytics

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 and by 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. 请参阅本文后面部分中的结构化日志记录See Structured logging later in this article.

配置类别和日志级别Configure categories and log levels

无需进行任何自定义配置,可以使用 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 的数据。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.

类别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.

Functions 运行时创建日志具有类别开头"主机。The Functions runtime creates logs with a category that begin with "Host." "函数已启动,""函数已执行"和"函数已完成"日志具有类别"Host.Executor"。The "function started," "function executed," and "function completed" logs have the category "Host.Executor."

如果在函数代码中编写日志,其类别为"函数"。If you write logs in your function code, their category is "Function."

日志级别Log levels

此外包括 Azure Functions 记录器日志级别与每个日志。The Azure Functions logger also includes a log level with every log. LogLevel 是一个枚举,整数代码指示相对重要性:LogLevel is an enumeration, and the integer code indicates relative importance:

LogLevelLogLevel 代码Code
跟踪Trace 00
调试Debug 11
信息Information 22
警告Warning 33
错误Error 44
严重Critical 55
None 66

日志级别 None 将在下一节中进行介绍。Log level None is explained in the next section.

在 host.json 中的日志配置Log configuration in host.json

Host.json 文件配置函数应用发送到 Application Insights 的日志记录数量。The host.json file configures how much logging a function app sends to Application Insights. 对于每个类别,均可以指示要发送的最小日志级别。For each category, you indicate the minimum log level to send. 有两个示例: 第一个示例针对Functions 版本 2.x 运行时(.NET Core) 和第二个示例适用于 1.x 版运行时。There are two examples: the first example targets the Functions version 2.x runtime (.NET Core) and the second example is for the version 1.x runtime.

版本 2.xVersion 2.x

v2.x 运行时使用 .NET Core 日志记录筛选器层次结构The v2.x runtime uses the .NET Core logging filter hierarchy.

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

版本 1.xVersion 1.x

{
  "logger": {
    "categoryFilter": {
      "defaultLevel": "Information",
      "categoryLevels": {
        "Host.Results": "Error",
        "Function": "Error",
        "Host.Aggregator": "Trace"
      }
    }
  }
}

此示例设置以下规则:This example sets up the following rules:

  • 具有类别的日志Host.ResultsFunction,仅发送Error级别及更高版本到 Application Insights。For logs with category Host.Results or Function, send only Error level and above to Application Insights. Warning 级别及以下级别的日志将被忽略。Logs for Warning level and below are ignored.
  • 对于 Host.Aggregator 类别的日志,将所有日志发送到 Application Insights。For logs with category Host.Aggregator, send all logs to Application Insights. Trace 日志级别与某些记录器称为 Verbose 的日志级别相同,但在 host.json 文件中请使用 TraceThe Trace log level is the same as what some loggers call Verbose, but use Trace in the host.json file.
  • 对于所有其他日志,仅向 Application Insights 发送 Information 级别及更高级别。For all other logs, send only Information level and above to Application Insights.

host.json 中的类别值控制所有以相同值开头的类别的日志记录。The category value in host.json controls logging for all categories that begin with the same value. Host 在中host.json控制日志记录Host.GeneralHost.ExecutorHost.Results,依次类推。Host in host.json controls logging for Host.General, Host.Executor, Host.Results, and so on.

如果 host.json 包含以相同字符串开头的多个类别,则先匹配较长的类别。If host.json includes multiple categories that start with the same string, the longer ones are matched first. 假设你想从运行时除外Host.Aggregator进行记录Error级别,但您想Host.AggregatorInformation级别:Suppose you want everything from the runtime except Host.Aggregator to log at Error level, but you want Host.Aggregator to log at the Information level:

版本 2.xVersion 2.x

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

版本 1.xVersion 1.x

{
  "logger": {
    "categoryFilter": {
      "defaultLevel": "Information",
      "categoryLevels": {
        "Host": "Error",
        "Function": "Error",
        "Host.Aggregator": "Information"
      }
    }
  }
}

若要禁止某个类别的所有日志,可以使用日志级别 NoneTo suppress all logs for a category, you can use log level None. 无日志写入与该类别和它上面没有日志级别。No logs are written with that category and there's no log level above it.

以下各部分描述了运行时创建的日志的主要类别。The following sections describe the main categories of logs that the runtime creates.

类别 Host.ResultsCategory Host.Results

这些日志在 Application Insights 中显示为“requests”。These logs show as "requests" in Application Insights. 它们指示函数的成功或失败。They 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.

类别 Host.AggregatorCategory Host.Aggregator

这些日志在一段可配置的时间内提供函数调用的计数和平均值。These 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.

日志位于 Application Insights 中的 customMetrics 表内。The logs are available in the customMetrics table in Application Insights. 示例包括运行、 成功率和持续时间数。Examples are the number of runs, success rate, and duration.

customMetrics 查询

所有这些日志写入在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.

其他类别Other categories

除了已经列出的类别,其余类别的所有日志在 Application Insights 的 traces 表中提供。All logs for categories other than the ones already listed are available in the traces table in Application Insights.

traces 查询

使用类别的开头的所有日志Host编写的 Functions 运行时。All logs with categories that begin with Host are written by the Functions runtime. "函数已启动"和"函数已完成"日志具有类别Host.ExecutorThe "Function started" and "Function completed" logs have category Host.Executor. 对于成功运行,这些日志是Information级别。For successful runs, these logs are Information level. 在记录异常Error级别。Exceptions are logged at Error level. 运行时还创建 Warning 级别日志,例如:已发送到病毒邮件队列的队列邮件。The runtime also creates Warning level logs, for example: queue messages sent to the poison queue.

由函数代码编写的日志具有类别Function,可以是任何日志级别。Logs written by your function code have category Function and can be any log level.

配置聚合器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 (五个 in 版本 1.x)。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:

版本 2.xVersion 2.x

{
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "maxTelemetryItemsPerSecond" : 20
      }
    }
  }
}

版本 1.xVersion 1.x

{
  "applicationInsights": {
    "sampling": {
      "isEnabled": true,
      "maxTelemetryItemsPerSecond" : 5
    }
  }
}

备注

采样是默认启用的。Sampling is enabled by default. 如果您看起来会丢失数据,您可能需要调整采样设置以适合特定监视方案。If you appear to be missing data, you might need to adjust the sampling settings to fit your particular monitoring scenario.

在 C# 函数中编写日志Write logs in C# functions

可以在 Application Insights 中显示为 traces 的函数代码中编写日志。You can write logs in your function code that appear as traces in Application Insights.

ILoggerILogger

在函数中使用 ILogger 参数,而不是 TraceWriter 参数。Use an ILogger parameter in your functions instead of a TraceWriter parameter. 通过使用创建的日志TraceWriter转到 Application Insights 中,但ILogger使你能够实现结构化日志记录Logs created by using TraceWriter go to Application Insights, but ILogger lets you do structured logging.

使用 ILogger 对象,可以调用 Log<level>ILogger 上的 扩展方法来创建日志。With an ILogger object, you call Log<level> extension methods on ILogger to create logs. 下面的代码编写Information日志类别为"函数"。The following code writes Information logs with category "Function."

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger logger)
{
    logger.LogInformation("Request for item with key={itemKey}.", id);

结构化日志记录Structured logging

占位符的顺序(而不是其名称)确定日志消息中使用的参数。The order of placeholders, not their names, determines which parameters are used in the log message. 假设有以下代码:Suppose you have the following code:

string partitionKey = "partitionKey";
string rowKey = "rowKey";
logger.LogInformation("partitionKey={partitionKey}, rowKey={rowKey}", partitionKey, rowKey);

如果保留相同的消息字符串并颠倒参数的顺序,则生成的消息文本将在错误的位置生成值。If you keep the same message string and reverse the order of the parameters, the resulting message text would have the values in the wrong places.

以这种方式处理占位符,以便可以执行结构化日志记录。Placeholders are handled this way so that you can do structured logging. Application Insights 存储参数名称 / 值对和消息字符串。Application Insights stores the parameter name-value pairs and the message string. 结果是消息参数变为可以查询的字段。The result is that the message arguments become fields that you can query on.

如果记录器方法调用类似于前面的示例,您可以查询该字段customDimensions.prop__rowKeyIf your logger method call looks like the previous example, you can query the field customDimensions.prop__rowKey. prop__以确保在运行时将添加和字段在函数代码的字段之间没有冲突添加添加前缀。The prop__ prefix is added to ensure there are no collisions between fields the runtime adds and fields your function code adds.

此外,可以通过引用字段 customDimensions.prop__{OriginalFormat} 查询原始消息字符串。You can also query on the original message string by referencing the field customDimensions.prop__{OriginalFormat}.

下面是 customDimensions 数据的示例 JSON 表示形式:Here's a sample JSON representation of customDimensions data:

{
  customDimensions: {
    "prop__{OriginalFormat}":"C# Queue trigger function processed: {message}",
    "Category":"Function",
    "LogLevel":"Information",
    "prop__message":"c9519cbf-b1e6-4b9b-bf24-cb7d10b1bb89"
  }
}

自定义指标日志记录Custom metrics logging

在 C# 脚本函数中,可以使用 ILogger 上的 LogMetric 扩展方法来在 Application Insights 中创建自定义指标。In C# script functions, you can use the LogMetric extension method on ILogger to create custom metrics in Application Insights. 下面是示例方法调用:Here's a sample method call:

logger.LogMetric("TestMetric", 1234);

此代码是调用的替代方法TrackMetric通过用于.NET 的 Application Insights API。This code is an alternative to calling TrackMetric by using the Application Insights API for .NET.

在 JavaScript 函数中写入日志Write logs in JavaScript functions

在 Node.js 函数中,使用 context.log 编写日志。In Node.js functions, use context.log to write logs. 结构化日志记录未启用。Structured logging isn't enabled.

context.log('JavaScript HTTP trigger function processed a request.' + context.invocationId);

自定义指标日志记录Custom metrics logging

运行时版本 1.x Functions 运行时,可以使用 Node.js 函数中context.log.metric方法来在 Application Insights 中创建自定义指标。When you're running on version 1.x of the Functions runtime, Node.js functions can use the context.log.metric method to create custom metrics in Application Insights. 此方法当前不支持在版本 2.x。This method isn't currently supported in version 2.x. 下面是示例方法调用:Here's a sample method call:

context.log.metric("TestMetric", 1234);

此代码是调用的替代方法trackMetric通过用于 Application Insights Node.js SDK。This code is an alternative to calling trackMetric by using the Node.js SDK for Application Insights.

登录自定义遥测C#函数Log custom telemetry in C# functions

可以使用 Microsoft.ApplicationInsights NuGet 程序包将自定义遥测数据发送到 Application Insights。You can use the Microsoft.ApplicationInsights NuGet package to send custom telemetry data to Application Insights. 以下 C# 示例使用自定义遥测 APIThe following C# example uses the custom telemetry API. 示例针对的是 .NET 类库,但对于 C# 脚本,Application Insights 代码是相同的。The example is for a .NET class library, but the Application Insights code is the same for C# script.

版本 2.xVersion 2.x

版本 2.x 运行时使用 Application Insights 中的较新功能自动将遥测与当前操作进行关联。The version 2.x runtime uses newer features in Application Insights to automatically correlate telemetry with the current operation. 无需手动设置该操作IdParentId,或Name字段。There's no need to manually set the operation Id, ParentId, or Name fields.

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

namespace functionapp0915
{
    public class HttpTrigger2
    {
        private readonly TelemetryClient telemetryClient;

        /// Using dependency injection will guarantee that you use the same configuration for telemetry collected automatically and manually.
        public HttpTrigger2(TelemetryConfiguration telemetryConfiguration)
        {
            this.telemetryClient = new TelemetryClient(telemetryConfiguration);
        }

        [FunctionName("HttpTrigger2")]
        public Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
            HttpRequest req, ExecutionContext context, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            DateTime start = DateTime.UtcNow;

            // Parse query parameter
            string name = req.Query
                .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                .Value;

            // Track an Event
            var evt = new EventTelemetry("Function called");
            evt.Context.User.Id = name;
            this.telemetryClient.TrackEvent(evt);

            // Track a Metric
            var metric = new MetricTelemetry("Test Metric", DateTime.Now.Millisecond);
            metric.Context.User.Id = name;
            this.telemetryClient.TrackMetric(metric);

            // Track a Dependency
            var dependency = new DependencyTelemetry
            {
                Name = "GET api/planets/1/",
                Target = "swapi.co",
                Data = "https://swapi.co/api/planets/1/",
                Timestamp = start,
                Duration = DateTime.UtcNow - start,
                Success = true
            };
            dependency.Context.User.Id = name;
            this.telemetryClient.TrackDependency(dependency);

            return Task.FromResult<IActionResult>(new OkResult());
        }
    }
}

版本 1.xVersion 1.x

using System;
using System.Net;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.WebJobs;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Linq;

namespace functionapp0915
{
    public static class HttpTrigger2
    {
        private static string key = TelemetryConfiguration.Active.InstrumentationKey = 
            System.Environment.GetEnvironmentVariable(
                "APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process);

        private static TelemetryClient telemetryClient = 
            new TelemetryClient() { InstrumentationKey = key };

        [FunctionName("HttpTrigger2")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequestMessage req, ExecutionContext context, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            DateTime start = DateTime.UtcNow;

            // Parse query parameter
            string name = req.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                .Value;

            // Get request body
            dynamic data = await req.Content.ReadAsAsync<object>();

            // Set name to query string or body data
            name = name ?? data?.name;
         
            // Track an Event
            var evt = new EventTelemetry("Function called");
            UpdateTelemetryContext(evt.Context, context, name);
            telemetryClient.TrackEvent(evt);
            
            // Track a Metric
            var metric = new MetricTelemetry("Test Metric", DateTime.Now.Millisecond);
            UpdateTelemetryContext(metric.Context, context, name);
            telemetryClient.TrackMetric(metric);
            
            // Track a Dependency
            var dependency = new DependencyTelemetry
                {
                    Name = "GET api/planets/1/",
                    Target = "swapi.co",
                    Data = "https://swapi.co/api/planets/1/",
                    Timestamp = start,
                    Duration = DateTime.UtcNow - start,
                    Success = true
                };
            UpdateTelemetryContext(dependency.Context, context, name);
            telemetryClient.TrackDependency(dependency);
        }
        
        // Correlate all telemetry with the current Function invocation
        private static void UpdateTelemetryContext(TelemetryContext context, ExecutionContext functionContext, string userName)
        {
            context.Operation.Id = functionContext.InvocationId.ToString();
            context.Operation.ParentId = functionContext.InvocationId.ToString();
            context.Operation.Name = functionContext.FunctionName;
            context.User.Id = userName;
        }
    }    
}

不要调用TrackRequestStartOperation<RequestTelemetry>因为您将看到函数调用的重复请求。Don't call TrackRequest or StartOperation<RequestTelemetry> because you'll see duplicate requests for a function invocation. Functions 运行时自动跟踪请求。The Functions runtime automatically tracks requests.

不要设置 telemetryClient.Context.Operation.IdDon't set telemetryClient.Context.Operation.Id. 许多函数同时运行时,此全局设置会导致不正确的关联。This global setting causes incorrect correlation when many functions are running simultaneously. 请改为创建新的遥测实例(DependencyTelemetryEventTelemetry)并修改其 Context 属性。Instead, create a new telemetry instance (DependencyTelemetry, EventTelemetry) and modify its Context property. 然后将遥测实例传入到 TelemetryClient 的相应 Track 方法(TrackDependency()TrackEvent())。Then pass in the telemetry instance to the corresponding Track method on TelemetryClient (TrackDependency(), TrackEvent()). 此方法可确保遥测具有当前函数调用的正确的相关详细信息。This method ensures that the telemetry has the correct correlation details for the current function invocation.

在 JavaScript 函数中的日志自定义遥测Log custom telemetry in JavaScript functions

Application Insights Node.js SDK 当前为 beta 版本。The Application Insights Node.js SDK is currently in beta. 下面是一些可将自定义遥测发送到 Application Insights 的示例代码:Here's some sample code that sends custom telemetry to Application Insights:

const appInsights = require("applicationinsights");
appInsights.setup();
const client = appInsights.defaultClient;

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    client.trackEvent({name: "my custom event", tagOverrides:{"ai.operation.id": context.invocationId}, properties: {customProperty2: "custom property value"}});
    client.trackException({exception: new Error("handled exceptions can be logged with this method"), tagOverrides:{"ai.operation.id": context.invocationId}});
    client.trackMetric({name: "custom metric", value: 3, tagOverrides:{"ai.operation.id": context.invocationId}});
    client.trackTrace({message: "trace message", tagOverrides:{"ai.operation.id": context.invocationId}});
    client.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:231, resultCode:0, success: true, dependencyTypeName: "ZSQL", tagOverrides:{"ai.operation.id": context.invocationId}});
    client.trackRequest({name:"GET /customers", url:"http://myserver/customers", duration:309, resultCode:200, success:true, tagOverrides:{"ai.operation.id": context.invocationId}});

    context.done();
};

tagOverrides参数集operation_Id到函数的调用 id。The tagOverrides parameter sets the operation_Id to the function's invocation ID. 通过此设置,可为给定的函数调用关联所有自动生成的遥测和自定义遥测。This setting enables you to correlate all of the automatically generated and custom telemetry for a given function invocation.

依赖项Dependencies

Functions v2 会自动收集有关 HTTP 请求、 服务总线和 SQL 的依赖项。Functions v2 automatically collects dependencies for HTTP requests, ServiceBus, and SQL.

可以编写自定义代码来显示依赖项。You can write custom code to show the dependencies. 有关示例,请参阅中的示例代码C#自定义遥测部分For examples, see the sample code in the C# custom telemetry section. 示例代码会导致应用程序映射在 Application Insights 中看起来像以下映像:The sample code results in an application map in Application Insights that looks like the following image:

应用程序映射

报告问题Report issues

若要报告 Functions 中的 Application Insights 集成问题,或提出建议或请求,请在 GitHub 中创建问题To report an issue with Application Insights integration in Functions, or to make a suggestion or request, create an issue in GitHub.

流式处理日志Streaming Logs

开发应用程序时,以近乎实时的方式查看日志记录信息通常很有用。While developing an application, it is often useful to see logging information in near-real time. 您可以查看生成的函数在 Azure 门户中或在本地计算机上的命令行会话日志文件的流。You can view a stream of log files being generated by your functions either in the Azure portal or in a command-line session on your local computer.

这相当于在调试期间函数时,看到的输出本地开发This is equivalent to the output seen when you debug your functions during local development. 有关详细信息,请参阅如何流式传输日志For more information, see How to stream logs.

备注

流式处理日志仅支持单个实例的 Functions 主机。Streaming logs support only a single instance of the Functions host. 当你的函数扩展到多个实例时,其他实例中的数据不会显示在日志流。When your function is scaled to multiple instances, data from other instances are not shown in the log stream. 实时指标 Stream在 Application Insights does 支持多个实例。The Live Metrics Stream in Application Insights does supported multiple instances. 虽然还在接近实时,流分析还基于采样的数据While also in near real time, streaming analytics are also based on sampled data.

门户Portal

若要在门户中查看流式处理日志,请选择平台功能函数应用程序中的选项卡。To view streaming logs in the portal, select the Platform features tab in your function app. 然后,在监视,选择日志流式处理Then, under Monitoring, choose Log streaming.

启用在门户中的流式处理日志

这将应用连接到日志流式处理服务和应用程序日志显示在窗口。This connects your app to the log streaming service and application logs are displayed in the window. 您可以切换应用程序日志Web 服务器日志You can toggle between Application logs and Web server logs.

在门户中查看流式日志

Azure CLIAzure CLI

可以使用启用流式处理日志Azure CLIYou can enable streaming logs by using the Azure CLI. 使用以下命令登录,请选择订阅并流式传输日志文件:Use the following commands to sign in, choose your subscription, and stream log files:

az login
az account list
az account set --subscription <subscriptionNameOrId>
az webapp log tail --resource-group <RESOURCE_GROUP_NAME> --name <FUNCTION_APP_NAME>

Azure PowerShellAzure PowerShell

可以使用启用流式处理日志Azure PowerShellYou can enable streaming logs by using Azure PowerShell. 对于 PowerShell,使用以下命令添加 Azure 帐户,请选择订阅并流式传输日志文件:For PowerShell, use the following commands to add your Azure account, choose your subscription, and stream log files:

Add-AzAccount
Get-AzSubscription
Get-AzSubscription -SubscriptionName "<subscription name>" | Select-AzSubscription
Get-AzWebSiteLog -Name <FUNCTION_APP_NAME> -Tail

禁用内置日志记录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

有关详细信息,请参阅以下资源:For more information, see the following resources: