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

将 ILogger、NLog、log4Net 或 System.Diagnostics.Trace 生成的 ASP.NET/ASP.NET Core 应用程序诊断跟踪日志发送到 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. 然后,可以浏览和搜索这些日志。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.

Note

是否需要日志捕获模块?Do you need the log-capture module? 它是第三方记录器的有用适配器。It's a useful adapter for third-party loggers.

在应用上安装记录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 Insights 添加到项目(如果尚未这样做)。Add 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.

Note

未看到 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:

  • Name 指定要收集的 EventSource 的名称。Name specifies the name of the EventSource to collect.
  • Level 指定要收集的日志记录级别。CriticalErrorInformationalLogAlwaysVerboseWarningLevel specifies the logging level to collect: Critical, Error, Informational, LogAlways, Verbose, or Warning.
  • Keywords(可选)指定要使用的关键字组合的整数值。Keywords (optional) specify the integer value of keyword combinations to use.

使用 DiagnosticSource 事件Use DiagnosticSource events

首先,安装 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,请添加一个 Name 属性设置为 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

可将 Windows 事件跟踪 (ETW) 事件配置为以跟踪的形式发送到 Application Insights。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.

Note

仅当托管 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 设置要收集的日志记录级别。Level sets the logging level to collect. 值可为 CriticalErrorInformationalLogAlwaysVerboseWarningIt can be Critical, Error, Informational, LogAlways, Verbose, or Warning.
  • Keywords(可选)设置要使用的关键字组合的整数值。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.
  • 找到与同一用户请求(具有相同的 OperationId)相关的其他系统日志数据。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.

Note

如果应用程序发送大量数据,并且使用的是 Application Insights SDK for ASP.NET 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 日志适配器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 Devloper 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.

有些日志条目未按预期出现I don't see some log entries that I expected

如果应用程序发送大量数据,并且使用的是 Application Insights SDK for ASP.NET 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