.Net Core 2.0调试日志记录已被破坏(仍然)

时间:2017-11-30 00:03:56

标签: c# logging .net-core

但是我配置了我的 appsettings.json appsettings.Development.json ,除非我手动添加 ConfigureLogging 到WebHostBuilder设置,如下:

var host = new WebHostBuilder()
                .UseConfiguration(config)
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Debug))
                .Build();

所以现在我想根据环境动态设置日志级别,但是在设置WebHostBuilder之前无法弄清楚如何在我的Program Main()中访问IHostingEnvironment实例引用我的 Startup 类。

我在这里看到的帖子的代码类似于以下内容,但它在GetService<Application>()行给出了语法错误,说静态类型不能用作类型参数:< / p>

var loggingLevel = LogLevel.Information;

IServiceCollection serviceCollection = new ServiceCollection();
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
var app = serviceProvider.GetService<Application>();
var hostingEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();
if (hostingEnvironment.IsDevelopment())
{
    loggingLevel = LogLevel.Debug;
}

有更好的方法吗?

这是我的 appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information"
    }
  },
  "Log4Net": {
    "ConfigFileRelativePath": "log4net.xml",
    "Repository": "NETCoreRepository"
  }
}

appsettings.Development.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug"
    }
  },
  "Swagger": {
    "FileName": "MyController.xml"
  }
}

我的项目的Debug面板确实设置了环境变量:

ASPNETCORE_ENVIRONMENT  Development

1 个答案:

答案 0 :(得分:1)

目前,我已经使用了环境变量:

var loggingLevel = LogLevel.Information;
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (env != null && env.ToLower().Equals("development"))
    loggingLevel = LogLevel.Debug;