c# - ILogger 不尊重 Application Insights 的日志级别
问题描述
我一直在尝试使用 ASP.NET Core 2.0 应用程序设置 Application Insights。在本地运行我的应用程序时,日志会按预期显示在 Application Insights 中。但是,当部署到 Azure 应用服务时,当日志被发送到 Application Insights 中的“请求”表时,“异常”或“跟踪”中不会显示任何日志。
唯一似乎解决此问题的方法是将以下代码行添加到 Startup.Configure():
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Information);
上面的解决方案是不可取的,因为我们希望根据环境配置不同的日志级别,因此基于配置的解决方案将是首选。另外,我的猜测是问题与配置有关,因为它在本地运行良好。Azure 中没有进行任何特殊配置。
这是整个 Startup.Configure():
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Information);
}
我的 Program.cs 如下:
namespace TestLoggingApplication
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseApplicationInsights()
.UseStartup<Startup>()
.Build();
}
}
应用程序的 appsettings.json 文件如下(InstrumentationKey 替换为隐私):
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Debug"
}
},
"Console": {
"LogLevel": {
"Default": "Debug"
}
},
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ApplicationInsights": {
"InstrumentationKey": "00000000-0000-0000-0000-000000000000"
}
}
解决方案
更新:此处提供了正确启用日志捕获的新说明。https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
启用日志记录支持的正确方法是使用loggerFactory.AddApplicationInsights()
inConfigure
方法。当您从 Visual Studio 运行时,您不需要此行,因为 VS 会在幕后为您完成。但是从VS外部运行时它不起作用,所以请添加loggerFactory.AddApplicationInsights
方法。
https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Logging
要根据环境获取不同的日志级别,请在条件语句中使用此行。类似于以下示例。
if(env.IsDeveleopment())
{
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Debug);
}
else if(env.IsPreProduction())
{
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Verbose);
}
else
{
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Warning);
}
推荐阅读
- git - 在远程服务器上创建项目并在 JetBrains PhpStorm 中从远程服务器使用 Git
- java - 常见模型和实用程序的正确位置,用于使用 spring-boot 的多模块 maven 项目
- java - 我不明白同步在我的代码中是如何工作的
- javascript - 如何使用 Pusher 在特定时间发送通知?
- css - 如何防止 uib-carousel 裁剪 uib-popover?
- php - PhpStorm 动态类型提示类属性
- python - python jupyter编码混乱
- android - fs::read_to_string 上的 unwrap() 导致致命信号 6 (SIGABRT),Android 中的代码 -1 (SI_QUEUE)
- python - 将标签数据添加到卷积神经网络的更好方法?
- javascript - 第二级侧边栏