首页 > 解决方案 > 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"
  }
}

标签: c#asp.net-core.net-coreazure-application-insightsazure-app-service-envrmnt

解决方案


更新:此处提供了正确启用日志捕获的新说明。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);

}

推荐阅读