你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 .NET 进行 Application Insights 日志记录

本文介绍如何使用 Microsoft.Extensions.Logging.ApplicationInsights 提供程序包在 .NET 应用中使用 Application Insights 捕获日志。 如果使用此提供程序,则可以使用 Application Insights 工具来查询和分析日志。

注意

以下文档依赖于 Application Insights 经典 API。 Application Insights 的长期计划是使用 OpenTelemetry 收集数据。 有关详细信息,请参阅为 .NET、Node.js、Python 和 Java 应用程序启用 Azure Monitor OpenTelemetry

注意

如果想要实施全方位的 Application Insights 遥测以及日志记录,请参阅为 ASP.NET 网站配置 Application Insights为 ASP.NET Core 应用程序配置 Application Insights

提示

Microsoft.ApplicationInsights.WorkerService NuGet 包(用于为后台服务启用 Application Insights)超出范围。 有关详细信息,请参阅 Application Insights for Worker Service 应用

ASP.NET Core 应用程序

若要将 Application Insights 日志记录添加到 ASP.NET Core 应用程序,请执行以下操作:

  1. 安装 Microsoft.Extensions.Logging.ApplicationInsights

  2. 添加 ApplicationInsightsLoggerProvider

using Microsoft.Extensions.Logging.ApplicationInsights;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Logging.AddApplicationInsights(
        configureTelemetryConfiguration: (config) => 
            config.ConnectionString = builder.Configuration.GetConnectionString("APPLICATIONINSIGHTS_CONNECTION_STRING"),
            configureApplicationInsightsLoggerOptions: (options) => { }
    );

builder.Logging.AddFilter<ApplicationInsightsLoggerProvider>("your-category", LogLevel.Trace);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

安装 NuGet 包,并且使用依赖项注入注册提供程序后,应用即可进行记录。 使用构造函数注入时,需要 ILogger 或泛型替代接口 ILogger<TCategoryName>。 解析这些实现后,ApplicationInsightsLoggerProvider 会提供它们。 记录的消息或异常会发送到 Application Insights。

考虑以下示例控制器:

public class ValuesController : ControllerBase
{
    private readonly ILogger _logger;

    public ValuesController(ILogger<ValuesController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        _logger.LogWarning("An example of a Warning trace..");
        _logger.LogError("An example of an Error level message");

        return new string[] { "value1", "value2" };
    }
}

有关详细信息,请参阅 ASP.NET Core 中的日志记录将从 ILogger 日志生成哪种类型的 Application Insights 遥测数据?可以在何处查看 Application Insights 中的 ILogger 日志?

控制台应用程序

若要将 Application Insights 日志记录添加到控制台应用程序,请先安装以下 NuGet 包:

以下示例使用 Microsoft.Extensions.Logging.ApplicationInsights 包,并演示控制台应用程序的默认行为。 Microsoft.Extensions.Logging.ApplicationInsights 应在控制台应用程序中使用,或者每当你希望在没有完整功能集(例如指标、分布式跟踪、采样和遥测初始值设定项)的情况下最低限度地实现 Application Insights 时使用。

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

using var channel = new InMemoryChannel();

try
{
    IServiceCollection services = new ServiceCollection();
    services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel);
    services.AddLogging(builder =>
    {
        // Only Application Insights is registered as a logger provider
        builder.AddApplicationInsights(
            configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>",
            configureApplicationInsightsLoggerOptions: (options) => { }
        );
    });

    IServiceProvider serviceProvider = services.BuildServiceProvider();
    ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();

    logger.LogInformation("Logger is working...");
}
finally
{
    // Explicitly call Flush() followed by Delay, as required in console apps.
    // This ensures that even if the application terminates, telemetry is sent to the back end.
    channel.Flush();

    await Task.Delay(TimeSpan.FromMilliseconds(1000));
}

有关详细信息,请参阅将从 ILogger 日志生成哪种类型的 Application Insights 遥测数据?可以在何处查看 Application Insights 中的 ILogger 日志?

日志记录范围

ApplicationInsightsLoggingProvider 支持日志范围。 默认启用范围。

如果范围的类型为 IReadOnlyCollection<KeyValuePair<string,object>>,则集合中的每个键值对都将作为自定义属性添加到 Application Insights 遥测数据中。 在下面的示例中,日志将作为 TraceTelemetry 被捕获,并且属性中将包含 ("MyKey", "MyValue")

using (_logger.BeginScope(new Dictionary<string, object> { ["MyKey"] = "MyValue" }))
{
    _logger.LogError("An example of an Error level message");
}

如果使用任何其他类型作为范围,它将存储在 Application Insights 遥测中的 Scope 属性下。 在下面的示例中,TraceTelemetry 具有包含该范围且名为 Scope 的属性。

    using (_logger.BeginScope("hello scope"))
    {
        _logger.LogError("An example of an Error level message");
    }

常见问题

将从 ILogger 日志生成哪种类型的 Application Insights 遥测数据? 可以在何处查看 Application Insights 中的 ILogger 日志?

ApplicationInsightsLoggerProvider 捕获 ILogger 日志并从中创建 TraceTelemetry。 如果将 Exception 对象传递给 ILogger 上的 Log 方法,则会创建 ExceptionTelemetry 而不是 TraceTelemetry

查看 ILogger 遥测

在 Azure 门户中:

  1. 转到 Azure 门户并访问 Application Insights 资源。
  2. 单击 Application Insights 中的“日志”部分。
  3. 使用 Kusto 查询语言 (KQL) 查询 ILogger 消息,通常存储在 traces 表中。
    • 示例查询:traces | where message contains "YourSearchTerm"
  4. 优化查询,按严重性、时间范围或特定消息内容筛选 ILogger 数据。

在 Visual Studio 中(本地调试程序):

  1. 在 Visual Studio 中以调试模式启动应用程序。
  2. 在应用程序运行时打开“诊断工具”窗口。
  3. 在“事件”选项卡中,ILogger 日志与其他遥测数据一起显示。
  4. 利用“诊断工具”窗口中的搜索和筛选功能来查找特定的 ILogger 消息。

若要始终发送 TraceTelemetry,请使用此代码片段:

builder.AddApplicationInsights(
    options => options.TrackExceptionsAsExceptionTelemetry = false);

为何某些 ILogger 日志包含的属性与其他日志不同?

Application Insights 使用对其他每项遥测功能所用的相同 TelemetryConfiguration 来捕获和发送 ILogger 日志。 但存在一种例外情况。 默认情况下,从 Program.cs 或 Startup.cs 登录时,TelemetryConfiguration 未完全设置。 来自以下位置的日志不具有默认配置,因此它们不会运行所有 TelemetryInitializer 实例和 TelemetryProcessor 实例。

我在使用独立包 Microsoft.Extensions.Logging.ApplicationInsights,想要手动记录更多的自定义遥测数据。 如何做到这一点?

使用独立包时,不会将 TelemetryClient 注入依赖项注入 (DI) 容器。 你需要创建 TelemetryClient 的新实例,并使用记录器提供程序所用的相同配置,如以下代码所示。 此要求可确保对所有自定义遥测和来自 ILogger 的遥测使用相同的配置。

public class MyController : ApiController
{
   // This TelemetryClient instance can be used to track additional telemetry through the TrackXXX() API.
   private readonly TelemetryClient _telemetryClient;
   private readonly ILogger _logger;

   public MyController(IOptions<TelemetryConfiguration> options, ILogger<MyController> logger)
   {
        _telemetryClient = new TelemetryClient(options.Value);
        _logger = logger;
   }  
}

注意

如果使用 Microsoft.ApplicationInsights.AspNetCore 包启用 Application Insights,请修改此代码,以便在构造函数中直接获取 TelemetryClient

我没有安装 SDK,而是使用 Azure Web 应用扩展来为 ASP.NET Core 应用程序启用 Application Insights。 如何使用新的提供程序?

Azure Web 应用中的 Application Insights 扩展使用新提供程序。 可以在应用程序的 appsettings.json 文件中修改筛选规则。

后续步骤