Remove console and debug loggers in ASP.NET Core 2.0 when in production mode
I would say the designed way to do this would be by changing the logging configuration not to log anything to those providers. But I understand that you want to remove any calls for production; and you can still do this properly in code.
You can simply access the hosting environment from the HostBuilderContext
that gets passed to the ConfigureLogging
lambda:
.ConfigureLogging((context, logging) =>
{
logging.AddConfiguration(context.Configuration.GetSection("Logging"));
if (context.HostingEnvironment.IsDevelopment())
{
logging.AddConsole();
logging.AddDebug();
}
});
Obviously, this alone does not help to undo what the CreateDefaultBuilder
call already set up. First, you would need to unregister those providers. For that, you can use the new ILoggingBuilder.ClearProviders
method:
.ConfigureLogging((context, logging) =>
{
// clear all previously registered providers
logging.ClearProviders();
// now register everything you *really* want
// …
});
This was introduced in response to this logging issue on GitHub.
I think you cant use the CreateDefaultBuilder then or set the LogLevels to None maybe. According to the docs you can use this.
public static void Main(string[] args)
{
var webHost = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true,
reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>()
.Build();
webHost.Run();
}
How to Add providers Section https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging?tabs=aspnetcore2x
Found another option, just add a Logging Filter for Console in your appsettings.json
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
"Console": {
"LogLevel": {
"Default": "None"
}
}
},
I found that it is better to remove a specific logging provider from the services as follows:
.ConfigureLogging((context, logging) => {
foreach (ServiceDescriptor serviceDescriptor in logging.Services)
{
if (serviceDescriptor.ImplementationType == typeof(Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider))
{
// remove ConsoleLoggerProvider service only
logging.Services.Remove(serviceDescriptor);
break;
}
}
// now you can register any new logging provider service; e.g.,
logging.AddLog4Net();
logging.AddEventSourceLogger();
})