在 Application Insights 中浏览 .NET/.NET Core 和 Python 跟踪日志Explore .NET/.NET Core and Python trace logs in Application Insights

将 ASP.NET/ASP.NET Core 应用程序的诊断跟踪日志从 ILogger、NLog、log4Net 或 System.Diagnostics.Trace 发送到 Azure Application InsightsSend diagnostic tracing logs for your ASP.NET/ASP.NET Core application from ILogger, NLog, log4Net, or System.Diagnostics.Trace to Azure Application Insights. 对于 Python 应用程序,使用适用于 Azure Monitor 的 OpenCensus Python 中的 AzureLogHandler 发送诊断跟踪日志。For Python applications, send diagnostic tracing logs using AzureLogHandler in OpenCensus Python for Azure Monitor. 然后,可以浏览并搜索它们。You can then explore and search them. 这些日志与应用程序中的其他日志文件合并,因此可以标识与每个用户请求关联的跟踪,并将它们与其他事件和异常报告关联。Those logs are merged with the other log files from your application, so you can identify traces that are associated with each user request and correlate them with other events and exception reports.

备注

是否需要日志捕获模块?Do you need the log-capture module? 它是适用于第三方记录器的适配器。It's a useful adapter for third-party loggers. 但是如果未使用 NLog、log4Net 或 System.Diagnostics.Trace,只需考虑直接调用 Application Insights TrackTrace()But if you aren't already using NLog, log4Net, or System.Diagnostics.Trace, consider just calling Application Insights TrackTrace() directly.

在应用上安装记录Install logging on your app

在项目中安装所选的日志框架,这将导致在 app.config 或 web.config 中生成一个条目。Install your chosen logging framework in your project, which should result in an entry in app.config or web.config.

 <configuration>
  <system.diagnostics>
    <trace>
      <listeners>
        <add name="myAppInsightsListener" type="Microsoft.ApplicationInsights.TraceListener.ApplicationInsightsTraceListener, Microsoft.ApplicationInsights.TraceListener" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

配置 Application Insights 以收集日志Configure Application Insights to collect logs

如果尚未执行此操作,请向项目添加 Application InsightsAdd Application Insights to your project if you haven't done that yet. 会看到一个选项以包括日志收集器。You'll see an option to include the log collector.

或者右键单击解决方案资源管理器中的项目以配置 Application Insights。Or right-click your project in Solution Explorer to Configure Application Insights. 选择“配置跟踪集合”选项。Select the Configure trace collection option.

备注

没有 Application Insights 菜单或日志收集器选项?No Application Insights menu or log collector option? 尝试故障排除Try Troubleshooting.

手动安装Manual installation

如果项目类型(例如 Windows 桌面项目)不受 Application Insights 安装程序支持,请使用此方法。Use this method if your project type isn't supported by the Application Insights installer (for example a Windows desktop project).

  1. 如果计划使用 log4Net 或 NLog,请在项目中安装它。If you plan to use log4Net or NLog, install it in your project.

  2. 在“解决方案资源管理器”中,右键单击项目并选择“管理 NuGet 包”.In Solution Explorer, right-click your project, and select Manage NuGet Packages.

  3. 搜索“Application Insights”。Search for "Application Insights."

  4. 选择以下包之一:Select one of the following packages:

NuGet 包安装必要的程序集,并在适用情况下修改 web.config 或 app.config。The NuGet package installs the necessary assemblies and modifies web.config or app.config if that's applicable.

ILoggerILogger

有关将 Azure Application Insights ILogger 实现与控制台应用程序及 ASP.NET Core 配合使用的示例,请参阅适用于 .NET Core ILogger 日志的 ApplicationInsightsLoggerProviderFor examples of using the Application Insights ILogger implementation with console applications and ASP.NET Core, see ApplicationInsightsLoggerProvider for .NET Core ILogger logs.

插入诊断日志调用Insert diagnostic log calls

如果使用 System.Diagnostics.Trace,则典型的调用将是:If you use System.Diagnostics.Trace, a typical call would be:

System.Diagnostics.Trace.TraceWarning("Slow response - database01");

如果首选 log4net 或 NLog,请使用:If you prefer log4net or NLog, use:

    logger.Warn("Slow response - database01");

使用 EventSource 事件Use EventSource events

可配置要作为跟踪发送到 Application Insights 的 System.Diagnostics.Tracing.EventSource 事件。You can configure System.Diagnostics.Tracing.EventSource events to be sent to Application Insights as traces. 首先,安装 Microsoft.ApplicationInsights.EventSourceListener NuGet 包。First, install the Microsoft.ApplicationInsights.EventSourceListener NuGet package. 然后编辑 ApplicationInsights.config 文件的 TelemetryModules 部分。Then edit the TelemetryModules section of the ApplicationInsights.config file.

    <Add Type="Microsoft.ApplicationInsights.EventSourceListener.EventSourceTelemetryModule, Microsoft.ApplicationInsights.EventSourceListener">
      <Sources>
        <Add Name="MyCompany" Level="Verbose" />
      </Sources>
    </Add>

可对每个资源设置以下参数:For each source, you can set the following parameters:

  • “名称”指定要收集的 EventSource 的名称。Name specifies the name of the EventSource to collect.
  • “级别”指定要收集的日志记录级别:严重、错误、信息性、LogAlways、详细或警告 。Level specifies the logging level to collect: Critical, Error, Informational, LogAlways, Verbose, or Warning.
  • “关键字”(可选)指定要使用的关键字组合的整数值。Keywords (optional) specify the integer value of keyword combinations to use.

使用 DiagnosticSource 事件Use DiagnosticSource events

可配置要作为跟踪发送到 Application Insights 的 System.Diagnostics.DiagnosticSource 事件。You can configure System.Diagnostics.DiagnosticSource events to be sent to Application Insights as traces. 首先,安装 Microsoft.ApplicationInsights.DiagnosticSourceListener NuGet 包。First, install the Microsoft.ApplicationInsights.DiagnosticSourceListener NuGet package. 然后编辑 ApplicationInsights.config 文件的“TelemetryModules”部分。Then edit the "TelemetryModules" section of the ApplicationInsights.config file.

    <Add Type="Microsoft.ApplicationInsights.DiagnosticSourceListener.DiagnosticSourceTelemetryModule, Microsoft.ApplicationInsights.DiagnosticSourceListener">
      <Sources>
        <Add Name="MyDiagnosticSourceName" />
      </Sources>
    </Add>

对于要跟踪的每个 DiagnosticSource,请在 DiagnosticSource 名称中添加包含“名称”属性集的项。For each DiagnosticSource you want to trace, add an entry with the Name attribute set to the name of your DiagnosticSource.

使用 ETW 事件Use ETW events

可配置要作为跟踪发送到 Application Insights 的 Windows 事件跟踪 (ETW) 事件。You can configure Event Tracing for Windows (ETW) events to be sent to Application Insights as traces. 首先,安装 Microsoft.ApplicationInsights.EtwCollector NuGet 包。First, install the Microsoft.ApplicationInsights.EtwCollector NuGet package. 然后编辑 ApplicationInsights.config 文件的“TelemetryModules”部分。Then edit the "TelemetryModules" section of the ApplicationInsights.config file.

备注

托管 SDK 的进程以“性能日志用户”或管理员成员身份运行时才可收集 ETW 事件。ETW events can only be collected if the process that hosts the SDK runs under an identity that's a member of Performance Log Users or Administrators.

    <Add Type="Microsoft.ApplicationInsights.EtwCollector.EtwCollectorTelemetryModule, Microsoft.ApplicationInsights.EtwCollector">
      <Sources>
        <Add ProviderName="MyCompanyEventSourceName" Level="Verbose" />
      </Sources>
    </Add>

可对每个资源设置以下参数:For each source, you can set the following parameters:

  • “ProviderName”是要收集的 ETW 提供程序的名称。ProviderName is the name of the ETW provider to collect.
  • “ProviderGuid”指定要收集的 ETW 提供程序的 GUID。ProviderGuid specifies the GUID of the ETW provider to collect. 可以使用它,而不是使用 ProviderNameIt can be used instead of ProviderName.
  • “级别”设置要收集的日志记录级别。Level sets the logging level to collect. 它可以是“严重”、“错误”、“信息性”、“LogAlways”、“详细”或“警告” 。It can be Critical, Error, Informational, LogAlways, Verbose, or Warning.
  • “关键字”(可选)设置要使用的关键字组合的整数值。Keywords (optional) set the integer value of keyword combinations to use.

直接使用跟踪 APIUse the Trace API directly

可以直接调用 Application Insights 跟踪 API。You can call the Application Insights trace API directly. 日志记录适配器使用此 API。The logging adapters use this API.

例如:For example:

var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackTrace("Slow response - database01");

TrackTrace 的一个优势是可将相对较长的数据放置在消息中。An advantage of TrackTrace is that you can put relatively long data in the message. 例如,可在此处对 POST 数据进行编码。For example, you can encode POST data there.

还可向消息添加严重性级别。You can also add a severity level to your message. 并像其他遥测一样,可以添加属性值以帮助筛选或搜索不同跟踪集。And, like other telemetry, you can add property values to help filter or search for different sets of traces. 例如:For example:

var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackTrace("Slow database response",
               SeverityLevel.Warning,
               new Dictionary<string,string> { {"database", db.ID} });

这样便可以在搜索中轻松筛选出与特定数据库相关的所有特定严重性级别的消息。This would enable you to easily filter out in Search all the messages of a particular severity level that relate to a particular database.

适用于 OpenCensus Python 的 AzureLogHandlerAzureLogHandler for OpenCensus Python

Azure Monitor 日志处理程序允许将 Python 日志导出到 Azure Monitor。The Azure Monitor Log Handler allows you to export Python logs to Azure Monitor.

使用适用于 Azure Monitor 的 OpenCensus Python SDK 检测应用程序。Instrument your application with the OpenCensus Python SDK for Azure Monitor.

此示例演示如何将警告级别日志发送到 Azure Monitor。This example shows how to send a warning level log to Azure Monitor.

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))
logger.warning('Hello, World!')

浏览日志Explore your logs

在调试模式下运行应用,或者实时部署它。Run your app in debug mode or deploy it live.

Application Insights 门户中的应用的概述窗格中,选择搜索In your app's overview pane in the Application Insights portal, select Search.

例如,可以:You can, for example:

  • 对日志跟踪或具有特定属性的项目进行筛选。Filter on log traces or on items with specific properties.
  • 检查详细信息中的特定项。Inspect a specific item in detail.
  • 查找与相同用户请求(具有相同的操作 ID)相关的其他系统日志数据。Find other system log data that relates to the same user request (has the same OperationId).
  • 将页面的配置另存为收藏夹。Save the configuration of a page as a favorite.

备注

如果应用程序发送大量数据,并且使用的是用于 ASP.NET 的 Application Insights SDK 2.0.0-beta3 或更高版本,则自适应采样功能可以正常运行,只发送一部分遥测数据。If your application sends a lot of data and you're using the Application Insights SDK for ASP.NET version 2.0.0-beta3 or later, the adaptive sampling feature may operate and send only a portion of your telemetry. 了解有关采样的详细信息。Learn more about sampling.

疑难解答Troubleshooting

对于 Java,我该怎么做?How do I do this for Java?

在 Java 无代码检测(推荐)中,日志是现成收集的,使用 Java 3.0 代理In Java codeless instrumentation (recommended) the logs are collected out of the box, use Java 3.0 agent.

如果使用的是 Java SDK,请使用 Java 日志适配器If you are using the Java SDK, use the Java log adapters.

项目上下文菜单上没有 Application Insights 选项There's no Application Insights option on the project context menu

  • 请确保 Developer Analytics Tools 安装在开发计算机上。Make sure that Developer Analytics Tools is installed on the development machine. 在 Visual Studio“工具” > “扩展和更新”中,查找“Developer Analytics Tools” 。At Visual Studio Tools > Extensions and Updates, look for Developer Analytics Tools. 如果它不在“已安装”选项卡中,请打开“联机”选项卡并安装它 。If it isn't on the Installed tab, open the Online tab and install it.
  • 这可能是 Developer Analytics Tools 不支持的项目类型。This might be a project type that Developer Analytics Tools doesn't support. 使用手动安装Use manual installation.

配置工具中没有日志适配器选项There's no log adapter option in the configuration tool

  • 首先安装记录框架。Install the logging framework first.
  • 如果使用的是 System.Diagnostics.Trace,请确保已在 web.config 中对其进行配置If you're using System.Diagnostics.Trace, make sure that you have it configured in web.config.
  • 确保已安装最新版本的 Application Insights。Make sure that you have the latest version of Application Insights. 在 Visual Studio中,转到“工具” > “扩展和更新”,并打开“更新”选项卡 。如果“Developer Analytics Tools”在此处,请选择以更新它。In Visual Studio, go to Tools > Extensions and Updates, and open the Updates tab. If Developer Analytics Tools is there, select it to update it.

出现错误消息“检测密钥不能为空”I get the "Instrumentation key cannot be empty" error message

可能在未安装 Application Insights 的情况下安装了日志记录适配器 Nuget 包。You probably installed the logging adapter Nuget package without installing Application Insights. 在解决方案资源管理器中,右键单击“ApplicationInsights.config”,然后选择“更新 Application Insights”。In Solution Explorer, right-click ApplicationInsights.config, and select Update Application Insights. 系统将提示你登录到 Azure 并创建 Application Insights 资源或重复使用现有资源。You'll be prompted to sign in to Azure and create an Application Insights resource or reuse an existing one. 这会解决此问题。That should fix the problem.

所有事件和请求都通过管道可能需要一些时间。It can take a while for all the events and requests to get through the pipeline.

会保留多少数据?How much data is retained?

多个因素会影响保留的数据量。Several factors affect the amount of data that's retained. 有关详细信息,请参阅客户事件指标页的限制部分。For more information, see the limits section of the customer event metrics page.

没有看到所需的一些日志条目I don't see some log entries that I expected

如果应用程序发送大量数据,并且使用的是用于 ASP.NET 的 Application Insights SDK 2.0.0-beta3 或更高版本,则自适应采样功能可以正常运行,只发送一部分遥测数据。If your application sends voluminous amounts of data and you're using the Application Insights SDK for ASP.NET version 2.0.0-beta3 or later, the adaptive sampling feature may operate and send only a portion of your telemetry. 了解有关采样的详细信息。Learn more about sampling.

后续步骤Next steps