【问题标题】:ILogger Not Respecting Log Level for Application InsightsILogger 不尊重 Application Insights 的日志级别
【发布时间】:2019-01-10 10:45:38
【问题描述】:

我一直在尝试使用 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-core azure-application-insights azure-app-service-envrmnt


    【解决方案1】:

    更新:此处提供了正确启用日志捕获的新说明。 https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger

    启用日志记录支持的正确方法是在Configure 方法中使用loggerFactory.AddApplicationInsights()。当您从 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);
    
    }
    

    【讨论】:

    • 答案解决了这个问题,即如何根据环境改变日志级别,但是如果你想使用配置来改变类别呢?例如,OP 的 appsettings.json 在 Information 中记录 Microsoft 和 System 类别,在 Debug 中记录所有其他内容。
    猜你喜欢
    • 1970-01-01
    • 2019-07-14
    • 2021-09-21
    • 2019-12-06
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多