ASP.NET Core 禁止命令行打印日志
CreateDefaultBuilder(args) 中默认添加了 ConsoleLoggerProvider,但是在某些场景如果不希望在命令行显示日志
方法一,遍历所有 LoggerProvider ,找到并移除 ConsoleLoggerProvider
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, loggingBuilder)=> { // remove ConsoleLoggerProvider service in Production Environment if (hostingContext.HostingEnvironment.IsProduction()) { foreach (ServiceDescriptor serviceDescriptor in loggingBuilder.Services) { if (serviceDescriptor.ImplementationType == typeof(Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider)) { loggingBuilder.Services.Remove(serviceDescriptor); break; } } } }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
方法二,清空 CreateDefaultBuilder(args) 添加的所有 LoggerProvider,然后重新添加自己需要的 LoggerProvider
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, loggingBuilder) => { // clear all previously registered providers loggingBuilder.ClearProviders(); // now register providers you need loggingBuilder.AddDebug(); loggingBuilder.AddEventSourceLogger(); if (hostingContext.HostingEnvironment.IsDevelopment()) { loggingBuilder.AddConsole(); } }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });