透過 .NET 使用 Application Insights 記錄功能

在本文中,您將了解如何使用 Microsoft.Extensions.Logging.ApplicationInsights 提供者套件,在 .NET 應用程式中使用 Application Insights 來擷取記錄。 如果您使用此提供者,就可以使用 Application Insights 工具來查詢及分析記錄。

注意

下列文件以 Application Insights 傳統 API 為依據。 Application Insights 的長期計劃是使用 OpenTelemetry 收集資料。 如需詳細資訊,請參閱啟用適用於 .NET、Node.js、Python 和 Java 應用程式的 Azure 監視器 OpenTelemetry

注意

如果您想要實作 Application Insights 遙測的完整範圍以及記錄,請參閱為 ASP.NET 網站設定 Application Insights適用於 ASP.NET Core 應用程式的 Application Insights

提示

用來背景服務啟用 Application Insights 的 Microsoft.ApplicationInsights.WorkerService NuGet 套件在範圍以外。 如需詳細資訊,請參閱背景工作服務應用程式的 Application Insights

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) 來查詢通常儲存在 traces 資料表中的 ILogger 訊息。
    • 範例查詢: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 用來擷取和傳送 ILogger 記錄的 TelemetryConfiguration 資訊,與用於所有其他遙測資料的相同。 但有例外狀況。 根據預設,從 Program.csStartup.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 Apps 擴充功能為我的 ASP.NET Core 應用程式啟用 Application Insights。 我該如何使用新的提供者?

Azure Web Apps 中的 Application Insights 擴充功能會使用新的提供者。 您可以在應用程式的 appsettings.json 檔案中修改篩選規則。

下一步