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

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

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

警告

我们建议新应用程序或客户使用 Azure Monitor OpenTelemetry 发行版来支持 Azure Monitor Application Insights。 Azure Monitor OpenTelemetry 发行版提供与 Application Insights SDK 类似的功能和体验。 可以使用适用于 .NETNode.jsPython 的迁移指南从 Application Insights SDK 进行迁移,但我们仍在努力添加更多功能以实现后向兼容性。

提示

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");
}

后续步骤