.Net Core 2.0调试日志记录仍然有问题

3

无论我如何配置appsettings.jsonappsettings.Development.json,除非我手动将ConfigureLogging添加到WebHostBuilder设置中,否则我无法在Information消息下方记录任何内容。

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

所以现在我想根据环境动态设置日志级别,但是在使用对我的Startup类的引用设置WebHostBuilder之前,无法找到如何访问IHostingEnvironment实例的方法。

我看到这里有一篇帖子,其中包含类似以下代码的内容,但是在GetService<Application>()行上它给了我一个语法错误,说静态类型不能用作类型参数

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"
  }
}

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

ASPNETCORE_ENVIRONMENT  Development

你能在这里发布你的appSettings吗?那通常定义了最低日志记录级别。 - MindingData
好的,已添加它们。我尝试了许多组合,例如在两者中都使用“Debug”,使用各种提供程序(Console等),直到我在WebHostBuilder中添加了对ConfigureLogging的调用,才使其正常工作。 - Alan
1个回答

1
目前,我选择了环境变量:

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

如果您想检查应用程序是否在特定环境中运行,您可能更喜欢使用 env.IsEnvironment("environmentname")。它会为您正确忽略大小写。 - Judy007
好的。我的问题是,我无法在实例化WebHostBuilder之前访问“env”(例如中的“hostingEnvironment”)。 - Alan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接