在本文中,您將了解如何使用 Microsoft.Extensions.Logging.ApplicationInsights
提供者套件,在 .NET 應用程式中使用 Application Insights 來擷取記錄。 如果您使用此提供者,就可以使用 Application Insights 工具來查詢及分析記錄。
警告
我們建議新的應用程式或客戶使用 Azure 監視器 OpenTelemetry 發行版本,以便支援 Azure 監視器 Application Insights。 Azure Monitor OpenTelemetry 分發版提供與 Application Insights SDK 類似的功能和體驗。 您可以使用適用於 .NET、Node.js 和 Python 的移轉指南,從 Application Insights SDK 移轉,但我們仍在努力新增更多功能以提供回溯相容性。
秘訣
- 根據預設,Application Insights 提供者只會傳送嚴重性為
Warning
或更高的記錄。 若要包含Information
或較低層級的記錄,請在 中appsettings.json
更新記錄層級設定。 - 如果您想要實作 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 應用程式:
新增
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");
}
下一步
- 若要檢閱常見問題 (FAQ),請參閱 使用 .NET 記錄常見問題
- 驗證您正在執行支援的 Application Insights SDK 版本 。
- 以 .NET 的身分登入
- ASP.NET Core 中的記錄
- Application Insights 中的 .NET 追蹤記錄