ASP.NET 使用 Application Insights 在 Azure 上进行核心跟踪日志记录

ASP.NET Core trace logging on Azure with Application Insights

我有一个 ASP.NET 核心 Web 项目部署到 Azure,并配置了 Application Insights。 Insights 可以正常接收请求等数据,但我无法让它显示我的日志。

我正在使用 vanilla Microsoft.Extensions.Logging 框架,并且在控制器操作上记录了一个测试错误

logger.LogError("Test application insights message");

在我的Startup.cs配置方法中我设置了

loggerFactory.AddAzureWebAppDiagnostics();

...并能成功看到错误信息出现在Azure logs streaming:

2017-04-14 11:06:00.313 +00:00 [Error] Test application insights message

但是,我也希望此消息出现在 Application Insights 跟踪中,但无处可寻。我想我需要配置 ILoggerFactory,但不确定如何配置,也找不到关于该主题的任何文档。

在此先感谢您的帮助

万一其他人试图解决这个问题,我得到了我想要的结果如下:

loggerFactory.AddApplicationInsights(app.ApplicationServices);

对我来说,只有当我在 Startup.cs 中将 InstrumentationKey 指定为 services.AddLogging 时它才有效,如下所示:

services.AddApplicationInsightsTelemetry();

services.AddLogging(builder =>
{
    // Only Application Insights is registered as a logger provider, get the key from appSettings.json file and add application insight
    var instrumentationKey = Configuration.GetValue<string>("ApplicationInsights:InstrumentationKey");
    builder.AddApplicationInsights(instrumentationKey);
});