Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core 2.0 debug logging is broken (still)

However I configure my appsettings.json and appsettings.Development.json, I cannot get anything logged below Information messages unless I manually add ConfigureLogging to the WebHostBuilder setup, as follows:

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

So now I'd like to set the log level dynamically based on the environment, but cannot figure out how to get access to an IHostingEnvironment instance in my Program Main() before setting up the WebHostBuilder with a reference to my Startup class.

I saw a post here with code similar to the following, however it's giving me a syntax error on the GetService<Application>() line, saying that static types cannot be used as type arguments:

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

Is there a better way to do this?

Here is my appsettings.json:

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

and appsettings.Development.json:

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

And my project's Debug panel does have the environment variable set:

ASPNETCORE_ENVIRONMENT  Development
like image 484
Alan Avatar asked Feb 02 '26 02:02

Alan


1 Answers

For now, I've gone with the environment variable:

var loggingLevel = LogLevel.Information;
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (env != null && env.ToLower().Equals("development"))
    loggingLevel = LogLevel.Debug;
like image 169
Alan Avatar answered Feb 03 '26 15:02

Alan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!