使用 .NET 進行 Application Insights 記錄

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

注意

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

注意

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

提示

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

ASP.NET Core 應用程式

若要將 Application Insights 記錄新增至 ASP.NET 核心應用程式:

  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 記錄?

ApplicationInsightsLoggerProviderILogger擷取記錄並從中建立TraceTelemetryException如果物件傳遞至 LogILogger方法,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 會擷取和傳送 ILogger 記錄,方法是使用用於所有其他遙測的相同 TelemetryConfiguration 資訊。 但有一個例外。 根據預設, TelemetryConfiguration 當您從 Program.csStartup.cs登入時,不會完全設定。 來自這些位置的記錄沒有預設組態,因此不會執行所有 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 檔案中修改篩選規則。

下一步