Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove console and debug loggers in ASP.NET Core 2.0 when in production mode

In ASP.NET Core 2.0 we have this

public static IWebHost BuildWebHost(string[] args) =>     WebHost.CreateDefaultBuilder(args)         .UseStartup<Startup>()         .Build(); 

That CreateDefaultBuilder(args) has many helpful defaults. However it contains this:

.ConfigureLogging((context, logging) => {     logging.AddConfiguration(context.Configuration.GetSection("Logging"));     logging.AddConsole();   // HERE IS THE PROBLEM     logging.AddDebug();     // HERE IS THE PROBLEM }) 

So the console and debug logging providers are always registered.

I used to register them like this

if (env.IsDevelopment()) {      // register them here } 

How do I remove/unregister them when running in production mode? I don't mean changing the logging level, I mean I don't want them registered at all in production mode.

like image 411
grokky Avatar asked Aug 31 '17 16:08

grokky


People also ask

How do I disable login in NET Core?

If you're using Host. CreateDefaultBuilder(), it adds a console logger provider by default. There are two simple ways to get rid of these logging messages: turn off logging in appsettings. json or remove the default logging providers.

What is the use of ILogger in .NET Core?

ILoggerFactory is a factory interface that we can use to create instances of the ILogger type and register logging providers. It acts as a wrapper for all the logger providers registered to it and a logger it creates can write to all the logger providers at once.


1 Answers

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.

like image 129
poke Avatar answered Oct 17 '22 23:10

poke