How to turn off the logging done by the ASP.NET core framework











up vote
33
down vote

favorite
7












How do I turn off the logging done by ASP.NET for each request e.g.




INFO 09:38:41 User profile is available. Using 'C:Usersxxxx xxxxAppDataLocalASP.NETDataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.

DEBUG 09:38:41 Hosting starting

DEBUG 09:38:41 Hosting started

INFO 09:38:41 Request starting HTTP/1.1 GET http://localhost:23369/

INFO 09:38:41 Request starting HTTP/1.1 DEBUG http://localhost:23369/ text/html
DEBUG 09:38:41 DEBUG requests are not supported

DEBUG 09:38:41 The request path / does not match a supported file type

DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index

DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index

INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index with arguments () - ModelState is Valid'

INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index

..




I couldn't find yet how I can turn this logging off...



This is my Configure method in the Startup class:



public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddProvider(new Log4NetProvider());

if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");

// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}

app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

app.UseStaticFiles();

app.UseIdentity();

// To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}


And this is my project.json file:



"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"log4net": "2.0.5",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
},

"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
"ef": "EntityFramework.Commands"
},

"frameworks": {
"dnx451": { }
},




Update:

My log4net provider was taken from here










share|improve this question




















  • 1




    1. Where exactly do you those logs you want to turn off. 2. How is your application hosted?
    – haim770
    Feb 7 '16 at 7:58










  • @haim770, I didn't understand the first question. 2. IIS express.
    – gdoron
    Feb 7 '16 at 8:13










  • You're explicitly registering log4net as your logging provider. Is it the log4net logs you want to turn off? Is it something you see in the Console? Do you simply want to change the tracing level?
    – haim770
    Feb 7 '16 at 8:14










  • @haim, I don't think it has anything to do with log4net, it's an adapter I wrote, it doesn't have access to the asp.net pipeline, which means asp.net internally calls the logger factory.
    – gdoron
    Feb 7 '16 at 8:39






  • 1




    You didn't specify where do you see/find those logs you want to disable so I had to assume it's log4net output. Again, where do you see the DEBUG 09:38:41 Hosting starting line?
    – haim770
    Feb 7 '16 at 8:41















up vote
33
down vote

favorite
7












How do I turn off the logging done by ASP.NET for each request e.g.




INFO 09:38:41 User profile is available. Using 'C:Usersxxxx xxxxAppDataLocalASP.NETDataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.

DEBUG 09:38:41 Hosting starting

DEBUG 09:38:41 Hosting started

INFO 09:38:41 Request starting HTTP/1.1 GET http://localhost:23369/

INFO 09:38:41 Request starting HTTP/1.1 DEBUG http://localhost:23369/ text/html
DEBUG 09:38:41 DEBUG requests are not supported

DEBUG 09:38:41 The request path / does not match a supported file type

DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index

DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index

INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index with arguments () - ModelState is Valid'

INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index

..




I couldn't find yet how I can turn this logging off...



This is my Configure method in the Startup class:



public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddProvider(new Log4NetProvider());

if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");

// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}

app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

app.UseStaticFiles();

app.UseIdentity();

// To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}


And this is my project.json file:



"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"log4net": "2.0.5",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
},

"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
"ef": "EntityFramework.Commands"
},

"frameworks": {
"dnx451": { }
},




Update:

My log4net provider was taken from here










share|improve this question




















  • 1




    1. Where exactly do you those logs you want to turn off. 2. How is your application hosted?
    – haim770
    Feb 7 '16 at 7:58










  • @haim770, I didn't understand the first question. 2. IIS express.
    – gdoron
    Feb 7 '16 at 8:13










  • You're explicitly registering log4net as your logging provider. Is it the log4net logs you want to turn off? Is it something you see in the Console? Do you simply want to change the tracing level?
    – haim770
    Feb 7 '16 at 8:14










  • @haim, I don't think it has anything to do with log4net, it's an adapter I wrote, it doesn't have access to the asp.net pipeline, which means asp.net internally calls the logger factory.
    – gdoron
    Feb 7 '16 at 8:39






  • 1




    You didn't specify where do you see/find those logs you want to disable so I had to assume it's log4net output. Again, where do you see the DEBUG 09:38:41 Hosting starting line?
    – haim770
    Feb 7 '16 at 8:41













up vote
33
down vote

favorite
7









up vote
33
down vote

favorite
7






7





How do I turn off the logging done by ASP.NET for each request e.g.




INFO 09:38:41 User profile is available. Using 'C:Usersxxxx xxxxAppDataLocalASP.NETDataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.

DEBUG 09:38:41 Hosting starting

DEBUG 09:38:41 Hosting started

INFO 09:38:41 Request starting HTTP/1.1 GET http://localhost:23369/

INFO 09:38:41 Request starting HTTP/1.1 DEBUG http://localhost:23369/ text/html
DEBUG 09:38:41 DEBUG requests are not supported

DEBUG 09:38:41 The request path / does not match a supported file type

DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index

DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index

INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index with arguments () - ModelState is Valid'

INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index

..




I couldn't find yet how I can turn this logging off...



This is my Configure method in the Startup class:



public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddProvider(new Log4NetProvider());

if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");

// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}

app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

app.UseStaticFiles();

app.UseIdentity();

// To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}


And this is my project.json file:



"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"log4net": "2.0.5",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
},

"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
"ef": "EntityFramework.Commands"
},

"frameworks": {
"dnx451": { }
},




Update:

My log4net provider was taken from here










share|improve this question















How do I turn off the logging done by ASP.NET for each request e.g.




INFO 09:38:41 User profile is available. Using 'C:Usersxxxx xxxxAppDataLocalASP.NETDataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.

DEBUG 09:38:41 Hosting starting

DEBUG 09:38:41 Hosting started

INFO 09:38:41 Request starting HTTP/1.1 GET http://localhost:23369/

INFO 09:38:41 Request starting HTTP/1.1 DEBUG http://localhost:23369/ text/html
DEBUG 09:38:41 DEBUG requests are not supported

DEBUG 09:38:41 The request path / does not match a supported file type

DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
DEBUG 09:38:41 Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'.
DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index

DEBUG 09:38:41 Executing action Forums.Controllers.HomeController.Index

INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index with arguments () - ModelState is Valid'

INFO 09:38:41 Executing action method Forums.Controllers.HomeController.Index

..




I couldn't find yet how I can turn this logging off...



This is my Configure method in the Startup class:



public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddProvider(new Log4NetProvider());

if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");

// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}

app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

app.UseStaticFiles();

app.UseIdentity();

// To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}


And this is my project.json file:



"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"log4net": "2.0.5",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
},

"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
"ef": "EntityFramework.Commands"
},

"frameworks": {
"dnx451": { }
},




Update:

My log4net provider was taken from here







c# logging asp.net-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 at 0:37









Camilo Terevinto

17.6k63464




17.6k63464










asked Feb 7 '16 at 7:51









gdoron

107k41242304




107k41242304








  • 1




    1. Where exactly do you those logs you want to turn off. 2. How is your application hosted?
    – haim770
    Feb 7 '16 at 7:58










  • @haim770, I didn't understand the first question. 2. IIS express.
    – gdoron
    Feb 7 '16 at 8:13










  • You're explicitly registering log4net as your logging provider. Is it the log4net logs you want to turn off? Is it something you see in the Console? Do you simply want to change the tracing level?
    – haim770
    Feb 7 '16 at 8:14










  • @haim, I don't think it has anything to do with log4net, it's an adapter I wrote, it doesn't have access to the asp.net pipeline, which means asp.net internally calls the logger factory.
    – gdoron
    Feb 7 '16 at 8:39






  • 1




    You didn't specify where do you see/find those logs you want to disable so I had to assume it's log4net output. Again, where do you see the DEBUG 09:38:41 Hosting starting line?
    – haim770
    Feb 7 '16 at 8:41














  • 1




    1. Where exactly do you those logs you want to turn off. 2. How is your application hosted?
    – haim770
    Feb 7 '16 at 7:58










  • @haim770, I didn't understand the first question. 2. IIS express.
    – gdoron
    Feb 7 '16 at 8:13










  • You're explicitly registering log4net as your logging provider. Is it the log4net logs you want to turn off? Is it something you see in the Console? Do you simply want to change the tracing level?
    – haim770
    Feb 7 '16 at 8:14










  • @haim, I don't think it has anything to do with log4net, it's an adapter I wrote, it doesn't have access to the asp.net pipeline, which means asp.net internally calls the logger factory.
    – gdoron
    Feb 7 '16 at 8:39






  • 1




    You didn't specify where do you see/find those logs you want to disable so I had to assume it's log4net output. Again, where do you see the DEBUG 09:38:41 Hosting starting line?
    – haim770
    Feb 7 '16 at 8:41








1




1




1. Where exactly do you those logs you want to turn off. 2. How is your application hosted?
– haim770
Feb 7 '16 at 7:58




1. Where exactly do you those logs you want to turn off. 2. How is your application hosted?
– haim770
Feb 7 '16 at 7:58












@haim770, I didn't understand the first question. 2. IIS express.
– gdoron
Feb 7 '16 at 8:13




@haim770, I didn't understand the first question. 2. IIS express.
– gdoron
Feb 7 '16 at 8:13












You're explicitly registering log4net as your logging provider. Is it the log4net logs you want to turn off? Is it something you see in the Console? Do you simply want to change the tracing level?
– haim770
Feb 7 '16 at 8:14




You're explicitly registering log4net as your logging provider. Is it the log4net logs you want to turn off? Is it something you see in the Console? Do you simply want to change the tracing level?
– haim770
Feb 7 '16 at 8:14












@haim, I don't think it has anything to do with log4net, it's an adapter I wrote, it doesn't have access to the asp.net pipeline, which means asp.net internally calls the logger factory.
– gdoron
Feb 7 '16 at 8:39




@haim, I don't think it has anything to do with log4net, it's an adapter I wrote, it doesn't have access to the asp.net pipeline, which means asp.net internally calls the logger factory.
– gdoron
Feb 7 '16 at 8:39




1




1




You didn't specify where do you see/find those logs you want to disable so I had to assume it's log4net output. Again, where do you see the DEBUG 09:38:41 Hosting starting line?
– haim770
Feb 7 '16 at 8:41




You didn't specify where do you see/find those logs you want to disable so I had to assume it's log4net output. Again, where do you see the DEBUG 09:38:41 Hosting starting line?
– haim770
Feb 7 '16 at 8:41












5 Answers
5






active

oldest

votes

















up vote
36
down vote



accepted










I'm not sure if I am missing something but don't you just want to raise the log level for the Microsoft logs?



Edit appsettings.json (assumes .AddJsonFile("appsettings.json", ...))



{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"System": "Information",
"Microsoft": "Information"


To



{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"System": "Information",
"Microsoft": "None"


Or the same modification via environment variables (assumes .AddEnvironmentVariables())



Logging:LogLevel:Microsoft=None


You can also be more specific, the following reduces most entries but leaves Microsoft.AspNetCore.Hosting.Internal.WebHost at Information.



"Microsoft": "Information",  
"Microsoft.AspNetCore.Mvc.Internal": "Warning",
"Microsoft.AspNetCore.Authentication": "Warning"


Appologies if this doesn't work for log4net






share|improve this answer



















  • 3




    I couldn't get this to work with Serilog, but it did work for the console logging when running the app on the command line (i.e. dotnet run).
    – Alyce
    Oct 20 '16 at 6:36








  • 1




    This config file is only used to control console logging unfortunately. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    – scott
    Apr 12 '17 at 15:52








  • 2




    @Alyce Serilog has filtering available as well: new LoggerConfiguration().Filter.ByExcluding(Matching.FromSource("Microsoft")) - see this for more info: stackoverflow.com/questions/38760381/…
    – Mani Gandham
    May 13 '17 at 22:18








  • 2




    You can also override so that only events above a certain level are logged for a specific source by using new LoggerConfiguration().MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    – Mani Gandham
    May 13 '17 at 22:43






  • 1




    Ooooooooh, that's what those strange "LogLevels" for Microsoft and System were for... I didn't realise that. Excellent tip.
    – Mike Gledhill
    May 17 at 8:08


















up vote
7
down vote













Since the new logging infrastructure is being used (by design) by asp.net itself (as well as other vendor code), it's up to the ILoggerProvider implementation to decide whether it wants to log that source or not.



Here's a revised implementation for log4net that adds a basic source filtering:



public class Log4NetProvider : ILoggerProvider
{
private static readonly NoopLogger _noopLogger = new NoopLogger();
private readonly Func<string, bool> _sourceFilterFunc;
private readonly ConcurrentDictionary<string, Log4NetLogger> _loggers = new ConcurrentDictionary<string, Log4NetLogger>();

public Log4NetProvider(Func<string, bool> sourceFilterFunc = null)
{
_sourceFilterFunc = sourceFilterFunc != null ? sourceFilterFunc : x => true;
}

public ILogger CreateLogger(string name)
{
if (!_sourceFilterFunc(name))
return _noopLogger;

return _loggers.GetOrAdd(name, x => new Log4NetLogger(name));
}

public void Dispose()
{
_loggers.Clear();
}

private class NoopLogger : ILogger
{
public IDisposable BeginScopeImpl(object state)
{
return null;
}

public bool IsEnabled(LogLevel logLevel)
{
return false;
}

public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
{
}
}
}


And the Log4NetAspExtensions:



public static void ConfigureLog4Net(this IApplicationEnvironment appEnv, string configFileRelativePath)
{
GlobalContext.Properties["appRoot"] = appEnv.ApplicationBasePath;
XmlConfigurator.Configure(new FileInfo(Path.Combine(appEnv.ApplicationBasePath, configFileRelativePath)));
}

public static void AddLog4Net(this ILoggerFactory loggerFactory, Func<string, bool> sourceFilterFunc = null)
{
loggerFactory.AddProvider(new Log4NetProvider(sourceFilterFunc));
}

public static void AddLog4Net(this ILoggerFactory loggerFactory)
{
loggerFactory.AddLog4Net(null);
}


Possible usage (in Startup.cs):



public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, ILoggerFactory loggerFactory)
{
appEnv.ConfigureLog4Net("log4net.xml");

loggerFactory.AddLog4Net(x => !x.StartsWith("Microsoft."));
}





share|improve this answer



















  • 1




    where is Log4NetLogger???
    – Totodile
    Mar 7 '16 at 16:50










  • @Totodile, I'm not sure I understand your question, but, Log4NetProvider does instantiate Log4NetLogger in CreateLogger()
    – haim770
    Mar 7 '16 at 18:50






  • 1




    I can't find the correct answer anywhere here, the correct one should be: loggerFactory.WithFilter(new FilterLoggerSettings { { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning }, { "MyOwnProject", LogLevel.Debug } }) .AddConsole(Configuration.GetSection("Logging")) .AddDebug();
    – timeshift
    Sep 7 '17 at 11:25




















up vote
7
down vote













If you're using Serilog to do your .Net core logging you can update your appsettings.json file to set the log levels like so:



"Serilog": {
"MinimumLevel": {
"Default": "Verbose",
"Override": {
"Microsoft": "Error",
"System": "Error"
}
},
"Properties": {
"Application": "your-app"
}
}


This allows you to only log errors from System/Microsoft while logging everything else as you'd like.






share|improve this answer





















  • This did the job for me. Thank You.
    – Sunny Okoro Awa
    Nov 19 at 13:49




















up vote
6
down vote













What have really worked for me was adding this in ASP.NET Core 2.0 project's Startup.cs file:



public void ConfigureServices(IServiceCollection services)
{
.
.
.

services.AddLogging(
builder =>
{
builder.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("NToastNotify", LogLevel.Warning)
.AddConsole();
});
}


This way you'll only get Warning level logs for logging info starting with the filters passed to builder.AddFilter.



My log4net.log file now doesn't show that huge amount of INFO logging spit by Microsoft and others.



More info here @ Microsoft Docs: Log filtering






share|improve this answer






























    up vote
    5
    down vote













    In and before ASP.NET 5 RC1 (now ASP.NET Core 1.0), you could do it via the logger factory, i.e.



    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
    // completely disable logging or use one of the other levels, such as Error, Critical, Warning etc.
    loggerFactory.MinimumLevel = LogLevel.None;
    }


    However, with the current branch (not released yet, but available via nightly builds), this has been removed. Now you need to pass the LogLevel per provider. Typically this is done via extension method.



    For the built in console logger, it would be loggerFactory.AddConsole(minimumLevel: LogLevel.Warning); for example.



    Since your logger provider is a custom one, you will have to configure it yourself. Take a look on how the console logger does it. It passes a delegate to the provider, that does the filtering.



    From GitHub Source:



    public static ILoggerFactory AddConsole(
    this ILoggerFactory factory,
    LogLevel minLevel,
    bool includeScopes)
    {
    factory.AddConsole((category, logLevel) => logLevel >= minLevel, includeScopes);
    return factory;
    }


    Of course instead of passing a delegate you can also directly set the log level of log4net.



    Update: To extend on what I've pointed out in the comments



    The ILoggerProvider is only a wrapper around the actual logging framework. In the simple case of ConsoleLoggerProvider, there is no framework as all behind it, just a simple Console.WriteLine call.



    In case of log4net, it's obvious from the example that logging can be enabled on a per level basis. This isn't possible with the .NET Core logger abstraction liked above, as the abstraction doesn't do any filtering.



    In a log4net ILoggerProvider one would simply route all log levels to the log4net net library and have it filter it.



    Based on the linked GitHub issue @haim770 created, you have the SourceContext for filtering and if log4net doesn't have a concept of SourceContext, you'll have to implement this in the provider. If it has a concept of SourceContext, then the provider needs to reroute/translate it into the structure log4net expects it.



    As you can see, the logger itself always stays unaware about internal specifics and implementation details of ASP.NET. The Log4NetProvider can't and shouldn't, because it's task is to translate/wrap around that api. Providers are just abstractions, so we don't have to leak implementation details into a library for example.






    share|improve this answer























    • This is not what I'm after. I do not want to change the logging level globally in my application, I just wish to turn off the ASP.NET logging which is tunneled through my provider. I deep dived into the source code, it's not a trivial task, I'm unhappy :(
      – gdoron
      Feb 7 '16 at 19:31










    • @gdoron: All logging requests will be tunneled to every registered ILoggingProvider. It's the task of the provider/logger to do the log level filtering. That's why MinimumLevel was removed and the now can only be set on per provider level
      – Tseng
      Feb 7 '16 at 19:37










    • I understand that all the loggers should get all logging requests. I just don't understand why there's no way to set ASP.NET itself logging to a specific level, why do I need my logging provider to be aware of all of the components, to me it seems like bad design.
      – gdoron
      Feb 7 '16 at 19:48










    • @gdoron: Because it's the providers responsibility. An application can have more than one provider, setting it globally may make no sense. For example you may have a ConsoleLogger for development, where you want to have all information, including "Trace" and "Debug" Level, on the other side you may want to have file logging which only logs Errors and Criticals. ASP.NET Core is made to be very flexible and be easy to add or remove a certain feature and for that reason. All you need to do is set your logger to Warning Level or higher, then Debug, Information and Trace level won't be logged
      – Tseng
      Feb 7 '16 at 19:52










    • Also your logger provider doesn't need to be aware of any components, just about the debug level, as this is what tells the logger what kind of messages it should log and which not.
      – Tseng
      Feb 7 '16 at 19:53











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35251078%2fhow-to-turn-off-the-logging-done-by-the-asp-net-core-framework%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    36
    down vote



    accepted










    I'm not sure if I am missing something but don't you just want to raise the log level for the Microsoft logs?



    Edit appsettings.json (assumes .AddJsonFile("appsettings.json", ...))



    {
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Trace",
    "System": "Information",
    "Microsoft": "Information"


    To



    {
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Trace",
    "System": "Information",
    "Microsoft": "None"


    Or the same modification via environment variables (assumes .AddEnvironmentVariables())



    Logging:LogLevel:Microsoft=None


    You can also be more specific, the following reduces most entries but leaves Microsoft.AspNetCore.Hosting.Internal.WebHost at Information.



    "Microsoft": "Information",  
    "Microsoft.AspNetCore.Mvc.Internal": "Warning",
    "Microsoft.AspNetCore.Authentication": "Warning"


    Appologies if this doesn't work for log4net






    share|improve this answer



















    • 3




      I couldn't get this to work with Serilog, but it did work for the console logging when running the app on the command line (i.e. dotnet run).
      – Alyce
      Oct 20 '16 at 6:36








    • 1




      This config file is only used to control console logging unfortunately. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      – scott
      Apr 12 '17 at 15:52








    • 2




      @Alyce Serilog has filtering available as well: new LoggerConfiguration().Filter.ByExcluding(Matching.FromSource("Microsoft")) - see this for more info: stackoverflow.com/questions/38760381/…
      – Mani Gandham
      May 13 '17 at 22:18








    • 2




      You can also override so that only events above a certain level are logged for a specific source by using new LoggerConfiguration().MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
      – Mani Gandham
      May 13 '17 at 22:43






    • 1




      Ooooooooh, that's what those strange "LogLevels" for Microsoft and System were for... I didn't realise that. Excellent tip.
      – Mike Gledhill
      May 17 at 8:08















    up vote
    36
    down vote



    accepted










    I'm not sure if I am missing something but don't you just want to raise the log level for the Microsoft logs?



    Edit appsettings.json (assumes .AddJsonFile("appsettings.json", ...))



    {
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Trace",
    "System": "Information",
    "Microsoft": "Information"


    To



    {
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Trace",
    "System": "Information",
    "Microsoft": "None"


    Or the same modification via environment variables (assumes .AddEnvironmentVariables())



    Logging:LogLevel:Microsoft=None


    You can also be more specific, the following reduces most entries but leaves Microsoft.AspNetCore.Hosting.Internal.WebHost at Information.



    "Microsoft": "Information",  
    "Microsoft.AspNetCore.Mvc.Internal": "Warning",
    "Microsoft.AspNetCore.Authentication": "Warning"


    Appologies if this doesn't work for log4net






    share|improve this answer



















    • 3




      I couldn't get this to work with Serilog, but it did work for the console logging when running the app on the command line (i.e. dotnet run).
      – Alyce
      Oct 20 '16 at 6:36








    • 1




      This config file is only used to control console logging unfortunately. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      – scott
      Apr 12 '17 at 15:52








    • 2




      @Alyce Serilog has filtering available as well: new LoggerConfiguration().Filter.ByExcluding(Matching.FromSource("Microsoft")) - see this for more info: stackoverflow.com/questions/38760381/…
      – Mani Gandham
      May 13 '17 at 22:18








    • 2




      You can also override so that only events above a certain level are logged for a specific source by using new LoggerConfiguration().MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
      – Mani Gandham
      May 13 '17 at 22:43






    • 1




      Ooooooooh, that's what those strange "LogLevels" for Microsoft and System were for... I didn't realise that. Excellent tip.
      – Mike Gledhill
      May 17 at 8:08













    up vote
    36
    down vote



    accepted







    up vote
    36
    down vote



    accepted






    I'm not sure if I am missing something but don't you just want to raise the log level for the Microsoft logs?



    Edit appsettings.json (assumes .AddJsonFile("appsettings.json", ...))



    {
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Trace",
    "System": "Information",
    "Microsoft": "Information"


    To



    {
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Trace",
    "System": "Information",
    "Microsoft": "None"


    Or the same modification via environment variables (assumes .AddEnvironmentVariables())



    Logging:LogLevel:Microsoft=None


    You can also be more specific, the following reduces most entries but leaves Microsoft.AspNetCore.Hosting.Internal.WebHost at Information.



    "Microsoft": "Information",  
    "Microsoft.AspNetCore.Mvc.Internal": "Warning",
    "Microsoft.AspNetCore.Authentication": "Warning"


    Appologies if this doesn't work for log4net






    share|improve this answer














    I'm not sure if I am missing something but don't you just want to raise the log level for the Microsoft logs?



    Edit appsettings.json (assumes .AddJsonFile("appsettings.json", ...))



    {
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Trace",
    "System": "Information",
    "Microsoft": "Information"


    To



    {
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Trace",
    "System": "Information",
    "Microsoft": "None"


    Or the same modification via environment variables (assumes .AddEnvironmentVariables())



    Logging:LogLevel:Microsoft=None


    You can also be more specific, the following reduces most entries but leaves Microsoft.AspNetCore.Hosting.Internal.WebHost at Information.



    "Microsoft": "Information",  
    "Microsoft.AspNetCore.Mvc.Internal": "Warning",
    "Microsoft.AspNetCore.Authentication": "Warning"


    Appologies if this doesn't work for log4net







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jun 16 '16 at 22:45

























    answered Jun 16 '16 at 22:39









    KCD

    6,08534655




    6,08534655








    • 3




      I couldn't get this to work with Serilog, but it did work for the console logging when running the app on the command line (i.e. dotnet run).
      – Alyce
      Oct 20 '16 at 6:36








    • 1




      This config file is only used to control console logging unfortunately. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      – scott
      Apr 12 '17 at 15:52








    • 2




      @Alyce Serilog has filtering available as well: new LoggerConfiguration().Filter.ByExcluding(Matching.FromSource("Microsoft")) - see this for more info: stackoverflow.com/questions/38760381/…
      – Mani Gandham
      May 13 '17 at 22:18








    • 2




      You can also override so that only events above a certain level are logged for a specific source by using new LoggerConfiguration().MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
      – Mani Gandham
      May 13 '17 at 22:43






    • 1




      Ooooooooh, that's what those strange "LogLevels" for Microsoft and System were for... I didn't realise that. Excellent tip.
      – Mike Gledhill
      May 17 at 8:08














    • 3




      I couldn't get this to work with Serilog, but it did work for the console logging when running the app on the command line (i.e. dotnet run).
      – Alyce
      Oct 20 '16 at 6:36








    • 1




      This config file is only used to control console logging unfortunately. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      – scott
      Apr 12 '17 at 15:52








    • 2




      @Alyce Serilog has filtering available as well: new LoggerConfiguration().Filter.ByExcluding(Matching.FromSource("Microsoft")) - see this for more info: stackoverflow.com/questions/38760381/…
      – Mani Gandham
      May 13 '17 at 22:18








    • 2




      You can also override so that only events above a certain level are logged for a specific source by using new LoggerConfiguration().MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
      – Mani Gandham
      May 13 '17 at 22:43






    • 1




      Ooooooooh, that's what those strange "LogLevels" for Microsoft and System were for... I didn't realise that. Excellent tip.
      – Mike Gledhill
      May 17 at 8:08








    3




    3




    I couldn't get this to work with Serilog, but it did work for the console logging when running the app on the command line (i.e. dotnet run).
    – Alyce
    Oct 20 '16 at 6:36






    I couldn't get this to work with Serilog, but it did work for the console logging when running the app on the command line (i.e. dotnet run).
    – Alyce
    Oct 20 '16 at 6:36






    1




    1




    This config file is only used to control console logging unfortunately. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    – scott
    Apr 12 '17 at 15:52






    This config file is only used to control console logging unfortunately. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    – scott
    Apr 12 '17 at 15:52






    2




    2




    @Alyce Serilog has filtering available as well: new LoggerConfiguration().Filter.ByExcluding(Matching.FromSource("Microsoft")) - see this for more info: stackoverflow.com/questions/38760381/…
    – Mani Gandham
    May 13 '17 at 22:18






    @Alyce Serilog has filtering available as well: new LoggerConfiguration().Filter.ByExcluding(Matching.FromSource("Microsoft")) - see this for more info: stackoverflow.com/questions/38760381/…
    – Mani Gandham
    May 13 '17 at 22:18






    2




    2




    You can also override so that only events above a certain level are logged for a specific source by using new LoggerConfiguration().MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    – Mani Gandham
    May 13 '17 at 22:43




    You can also override so that only events above a certain level are logged for a specific source by using new LoggerConfiguration().MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    – Mani Gandham
    May 13 '17 at 22:43




    1




    1




    Ooooooooh, that's what those strange "LogLevels" for Microsoft and System were for... I didn't realise that. Excellent tip.
    – Mike Gledhill
    May 17 at 8:08




    Ooooooooh, that's what those strange "LogLevels" for Microsoft and System were for... I didn't realise that. Excellent tip.
    – Mike Gledhill
    May 17 at 8:08












    up vote
    7
    down vote













    Since the new logging infrastructure is being used (by design) by asp.net itself (as well as other vendor code), it's up to the ILoggerProvider implementation to decide whether it wants to log that source or not.



    Here's a revised implementation for log4net that adds a basic source filtering:



    public class Log4NetProvider : ILoggerProvider
    {
    private static readonly NoopLogger _noopLogger = new NoopLogger();
    private readonly Func<string, bool> _sourceFilterFunc;
    private readonly ConcurrentDictionary<string, Log4NetLogger> _loggers = new ConcurrentDictionary<string, Log4NetLogger>();

    public Log4NetProvider(Func<string, bool> sourceFilterFunc = null)
    {
    _sourceFilterFunc = sourceFilterFunc != null ? sourceFilterFunc : x => true;
    }

    public ILogger CreateLogger(string name)
    {
    if (!_sourceFilterFunc(name))
    return _noopLogger;

    return _loggers.GetOrAdd(name, x => new Log4NetLogger(name));
    }

    public void Dispose()
    {
    _loggers.Clear();
    }

    private class NoopLogger : ILogger
    {
    public IDisposable BeginScopeImpl(object state)
    {
    return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
    return false;
    }

    public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
    {
    }
    }
    }


    And the Log4NetAspExtensions:



    public static void ConfigureLog4Net(this IApplicationEnvironment appEnv, string configFileRelativePath)
    {
    GlobalContext.Properties["appRoot"] = appEnv.ApplicationBasePath;
    XmlConfigurator.Configure(new FileInfo(Path.Combine(appEnv.ApplicationBasePath, configFileRelativePath)));
    }

    public static void AddLog4Net(this ILoggerFactory loggerFactory, Func<string, bool> sourceFilterFunc = null)
    {
    loggerFactory.AddProvider(new Log4NetProvider(sourceFilterFunc));
    }

    public static void AddLog4Net(this ILoggerFactory loggerFactory)
    {
    loggerFactory.AddLog4Net(null);
    }


    Possible usage (in Startup.cs):



    public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, ILoggerFactory loggerFactory)
    {
    appEnv.ConfigureLog4Net("log4net.xml");

    loggerFactory.AddLog4Net(x => !x.StartsWith("Microsoft."));
    }





    share|improve this answer



















    • 1




      where is Log4NetLogger???
      – Totodile
      Mar 7 '16 at 16:50










    • @Totodile, I'm not sure I understand your question, but, Log4NetProvider does instantiate Log4NetLogger in CreateLogger()
      – haim770
      Mar 7 '16 at 18:50






    • 1




      I can't find the correct answer anywhere here, the correct one should be: loggerFactory.WithFilter(new FilterLoggerSettings { { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning }, { "MyOwnProject", LogLevel.Debug } }) .AddConsole(Configuration.GetSection("Logging")) .AddDebug();
      – timeshift
      Sep 7 '17 at 11:25

















    up vote
    7
    down vote













    Since the new logging infrastructure is being used (by design) by asp.net itself (as well as other vendor code), it's up to the ILoggerProvider implementation to decide whether it wants to log that source or not.



    Here's a revised implementation for log4net that adds a basic source filtering:



    public class Log4NetProvider : ILoggerProvider
    {
    private static readonly NoopLogger _noopLogger = new NoopLogger();
    private readonly Func<string, bool> _sourceFilterFunc;
    private readonly ConcurrentDictionary<string, Log4NetLogger> _loggers = new ConcurrentDictionary<string, Log4NetLogger>();

    public Log4NetProvider(Func<string, bool> sourceFilterFunc = null)
    {
    _sourceFilterFunc = sourceFilterFunc != null ? sourceFilterFunc : x => true;
    }

    public ILogger CreateLogger(string name)
    {
    if (!_sourceFilterFunc(name))
    return _noopLogger;

    return _loggers.GetOrAdd(name, x => new Log4NetLogger(name));
    }

    public void Dispose()
    {
    _loggers.Clear();
    }

    private class NoopLogger : ILogger
    {
    public IDisposable BeginScopeImpl(object state)
    {
    return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
    return false;
    }

    public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
    {
    }
    }
    }


    And the Log4NetAspExtensions:



    public static void ConfigureLog4Net(this IApplicationEnvironment appEnv, string configFileRelativePath)
    {
    GlobalContext.Properties["appRoot"] = appEnv.ApplicationBasePath;
    XmlConfigurator.Configure(new FileInfo(Path.Combine(appEnv.ApplicationBasePath, configFileRelativePath)));
    }

    public static void AddLog4Net(this ILoggerFactory loggerFactory, Func<string, bool> sourceFilterFunc = null)
    {
    loggerFactory.AddProvider(new Log4NetProvider(sourceFilterFunc));
    }

    public static void AddLog4Net(this ILoggerFactory loggerFactory)
    {
    loggerFactory.AddLog4Net(null);
    }


    Possible usage (in Startup.cs):



    public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, ILoggerFactory loggerFactory)
    {
    appEnv.ConfigureLog4Net("log4net.xml");

    loggerFactory.AddLog4Net(x => !x.StartsWith("Microsoft."));
    }





    share|improve this answer



















    • 1




      where is Log4NetLogger???
      – Totodile
      Mar 7 '16 at 16:50










    • @Totodile, I'm not sure I understand your question, but, Log4NetProvider does instantiate Log4NetLogger in CreateLogger()
      – haim770
      Mar 7 '16 at 18:50






    • 1




      I can't find the correct answer anywhere here, the correct one should be: loggerFactory.WithFilter(new FilterLoggerSettings { { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning }, { "MyOwnProject", LogLevel.Debug } }) .AddConsole(Configuration.GetSection("Logging")) .AddDebug();
      – timeshift
      Sep 7 '17 at 11:25















    up vote
    7
    down vote










    up vote
    7
    down vote









    Since the new logging infrastructure is being used (by design) by asp.net itself (as well as other vendor code), it's up to the ILoggerProvider implementation to decide whether it wants to log that source or not.



    Here's a revised implementation for log4net that adds a basic source filtering:



    public class Log4NetProvider : ILoggerProvider
    {
    private static readonly NoopLogger _noopLogger = new NoopLogger();
    private readonly Func<string, bool> _sourceFilterFunc;
    private readonly ConcurrentDictionary<string, Log4NetLogger> _loggers = new ConcurrentDictionary<string, Log4NetLogger>();

    public Log4NetProvider(Func<string, bool> sourceFilterFunc = null)
    {
    _sourceFilterFunc = sourceFilterFunc != null ? sourceFilterFunc : x => true;
    }

    public ILogger CreateLogger(string name)
    {
    if (!_sourceFilterFunc(name))
    return _noopLogger;

    return _loggers.GetOrAdd(name, x => new Log4NetLogger(name));
    }

    public void Dispose()
    {
    _loggers.Clear();
    }

    private class NoopLogger : ILogger
    {
    public IDisposable BeginScopeImpl(object state)
    {
    return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
    return false;
    }

    public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
    {
    }
    }
    }


    And the Log4NetAspExtensions:



    public static void ConfigureLog4Net(this IApplicationEnvironment appEnv, string configFileRelativePath)
    {
    GlobalContext.Properties["appRoot"] = appEnv.ApplicationBasePath;
    XmlConfigurator.Configure(new FileInfo(Path.Combine(appEnv.ApplicationBasePath, configFileRelativePath)));
    }

    public static void AddLog4Net(this ILoggerFactory loggerFactory, Func<string, bool> sourceFilterFunc = null)
    {
    loggerFactory.AddProvider(new Log4NetProvider(sourceFilterFunc));
    }

    public static void AddLog4Net(this ILoggerFactory loggerFactory)
    {
    loggerFactory.AddLog4Net(null);
    }


    Possible usage (in Startup.cs):



    public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, ILoggerFactory loggerFactory)
    {
    appEnv.ConfigureLog4Net("log4net.xml");

    loggerFactory.AddLog4Net(x => !x.StartsWith("Microsoft."));
    }





    share|improve this answer














    Since the new logging infrastructure is being used (by design) by asp.net itself (as well as other vendor code), it's up to the ILoggerProvider implementation to decide whether it wants to log that source or not.



    Here's a revised implementation for log4net that adds a basic source filtering:



    public class Log4NetProvider : ILoggerProvider
    {
    private static readonly NoopLogger _noopLogger = new NoopLogger();
    private readonly Func<string, bool> _sourceFilterFunc;
    private readonly ConcurrentDictionary<string, Log4NetLogger> _loggers = new ConcurrentDictionary<string, Log4NetLogger>();

    public Log4NetProvider(Func<string, bool> sourceFilterFunc = null)
    {
    _sourceFilterFunc = sourceFilterFunc != null ? sourceFilterFunc : x => true;
    }

    public ILogger CreateLogger(string name)
    {
    if (!_sourceFilterFunc(name))
    return _noopLogger;

    return _loggers.GetOrAdd(name, x => new Log4NetLogger(name));
    }

    public void Dispose()
    {
    _loggers.Clear();
    }

    private class NoopLogger : ILogger
    {
    public IDisposable BeginScopeImpl(object state)
    {
    return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
    return false;
    }

    public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
    {
    }
    }
    }


    And the Log4NetAspExtensions:



    public static void ConfigureLog4Net(this IApplicationEnvironment appEnv, string configFileRelativePath)
    {
    GlobalContext.Properties["appRoot"] = appEnv.ApplicationBasePath;
    XmlConfigurator.Configure(new FileInfo(Path.Combine(appEnv.ApplicationBasePath, configFileRelativePath)));
    }

    public static void AddLog4Net(this ILoggerFactory loggerFactory, Func<string, bool> sourceFilterFunc = null)
    {
    loggerFactory.AddProvider(new Log4NetProvider(sourceFilterFunc));
    }

    public static void AddLog4Net(this ILoggerFactory loggerFactory)
    {
    loggerFactory.AddLog4Net(null);
    }


    Possible usage (in Startup.cs):



    public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, ILoggerFactory loggerFactory)
    {
    appEnv.ConfigureLog4Net("log4net.xml");

    loggerFactory.AddLog4Net(x => !x.StartsWith("Microsoft."));
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Feb 8 '16 at 8:59

























    answered Feb 8 '16 at 8:37









    haim770

    39k474108




    39k474108








    • 1




      where is Log4NetLogger???
      – Totodile
      Mar 7 '16 at 16:50










    • @Totodile, I'm not sure I understand your question, but, Log4NetProvider does instantiate Log4NetLogger in CreateLogger()
      – haim770
      Mar 7 '16 at 18:50






    • 1




      I can't find the correct answer anywhere here, the correct one should be: loggerFactory.WithFilter(new FilterLoggerSettings { { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning }, { "MyOwnProject", LogLevel.Debug } }) .AddConsole(Configuration.GetSection("Logging")) .AddDebug();
      – timeshift
      Sep 7 '17 at 11:25
















    • 1




      where is Log4NetLogger???
      – Totodile
      Mar 7 '16 at 16:50










    • @Totodile, I'm not sure I understand your question, but, Log4NetProvider does instantiate Log4NetLogger in CreateLogger()
      – haim770
      Mar 7 '16 at 18:50






    • 1




      I can't find the correct answer anywhere here, the correct one should be: loggerFactory.WithFilter(new FilterLoggerSettings { { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning }, { "MyOwnProject", LogLevel.Debug } }) .AddConsole(Configuration.GetSection("Logging")) .AddDebug();
      – timeshift
      Sep 7 '17 at 11:25










    1




    1




    where is Log4NetLogger???
    – Totodile
    Mar 7 '16 at 16:50




    where is Log4NetLogger???
    – Totodile
    Mar 7 '16 at 16:50












    @Totodile, I'm not sure I understand your question, but, Log4NetProvider does instantiate Log4NetLogger in CreateLogger()
    – haim770
    Mar 7 '16 at 18:50




    @Totodile, I'm not sure I understand your question, but, Log4NetProvider does instantiate Log4NetLogger in CreateLogger()
    – haim770
    Mar 7 '16 at 18:50




    1




    1




    I can't find the correct answer anywhere here, the correct one should be: loggerFactory.WithFilter(new FilterLoggerSettings { { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning }, { "MyOwnProject", LogLevel.Debug } }) .AddConsole(Configuration.GetSection("Logging")) .AddDebug();
    – timeshift
    Sep 7 '17 at 11:25






    I can't find the correct answer anywhere here, the correct one should be: loggerFactory.WithFilter(new FilterLoggerSettings { { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning }, { "MyOwnProject", LogLevel.Debug } }) .AddConsole(Configuration.GetSection("Logging")) .AddDebug();
    – timeshift
    Sep 7 '17 at 11:25












    up vote
    7
    down vote













    If you're using Serilog to do your .Net core logging you can update your appsettings.json file to set the log levels like so:



    "Serilog": {
    "MinimumLevel": {
    "Default": "Verbose",
    "Override": {
    "Microsoft": "Error",
    "System": "Error"
    }
    },
    "Properties": {
    "Application": "your-app"
    }
    }


    This allows you to only log errors from System/Microsoft while logging everything else as you'd like.






    share|improve this answer





















    • This did the job for me. Thank You.
      – Sunny Okoro Awa
      Nov 19 at 13:49

















    up vote
    7
    down vote













    If you're using Serilog to do your .Net core logging you can update your appsettings.json file to set the log levels like so:



    "Serilog": {
    "MinimumLevel": {
    "Default": "Verbose",
    "Override": {
    "Microsoft": "Error",
    "System": "Error"
    }
    },
    "Properties": {
    "Application": "your-app"
    }
    }


    This allows you to only log errors from System/Microsoft while logging everything else as you'd like.






    share|improve this answer





















    • This did the job for me. Thank You.
      – Sunny Okoro Awa
      Nov 19 at 13:49















    up vote
    7
    down vote










    up vote
    7
    down vote









    If you're using Serilog to do your .Net core logging you can update your appsettings.json file to set the log levels like so:



    "Serilog": {
    "MinimumLevel": {
    "Default": "Verbose",
    "Override": {
    "Microsoft": "Error",
    "System": "Error"
    }
    },
    "Properties": {
    "Application": "your-app"
    }
    }


    This allows you to only log errors from System/Microsoft while logging everything else as you'd like.






    share|improve this answer












    If you're using Serilog to do your .Net core logging you can update your appsettings.json file to set the log levels like so:



    "Serilog": {
    "MinimumLevel": {
    "Default": "Verbose",
    "Override": {
    "Microsoft": "Error",
    "System": "Error"
    }
    },
    "Properties": {
    "Application": "your-app"
    }
    }


    This allows you to only log errors from System/Microsoft while logging everything else as you'd like.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Sep 13 '17 at 18:52









    Tony Ranieri

    6501128




    6501128












    • This did the job for me. Thank You.
      – Sunny Okoro Awa
      Nov 19 at 13:49




















    • This did the job for me. Thank You.
      – Sunny Okoro Awa
      Nov 19 at 13:49


















    This did the job for me. Thank You.
    – Sunny Okoro Awa
    Nov 19 at 13:49






    This did the job for me. Thank You.
    – Sunny Okoro Awa
    Nov 19 at 13:49












    up vote
    6
    down vote













    What have really worked for me was adding this in ASP.NET Core 2.0 project's Startup.cs file:



    public void ConfigureServices(IServiceCollection services)
    {
    .
    .
    .

    services.AddLogging(
    builder =>
    {
    builder.AddFilter("Microsoft", LogLevel.Warning)
    .AddFilter("System", LogLevel.Warning)
    .AddFilter("NToastNotify", LogLevel.Warning)
    .AddConsole();
    });
    }


    This way you'll only get Warning level logs for logging info starting with the filters passed to builder.AddFilter.



    My log4net.log file now doesn't show that huge amount of INFO logging spit by Microsoft and others.



    More info here @ Microsoft Docs: Log filtering






    share|improve this answer



























      up vote
      6
      down vote













      What have really worked for me was adding this in ASP.NET Core 2.0 project's Startup.cs file:



      public void ConfigureServices(IServiceCollection services)
      {
      .
      .
      .

      services.AddLogging(
      builder =>
      {
      builder.AddFilter("Microsoft", LogLevel.Warning)
      .AddFilter("System", LogLevel.Warning)
      .AddFilter("NToastNotify", LogLevel.Warning)
      .AddConsole();
      });
      }


      This way you'll only get Warning level logs for logging info starting with the filters passed to builder.AddFilter.



      My log4net.log file now doesn't show that huge amount of INFO logging spit by Microsoft and others.



      More info here @ Microsoft Docs: Log filtering






      share|improve this answer

























        up vote
        6
        down vote










        up vote
        6
        down vote









        What have really worked for me was adding this in ASP.NET Core 2.0 project's Startup.cs file:



        public void ConfigureServices(IServiceCollection services)
        {
        .
        .
        .

        services.AddLogging(
        builder =>
        {
        builder.AddFilter("Microsoft", LogLevel.Warning)
        .AddFilter("System", LogLevel.Warning)
        .AddFilter("NToastNotify", LogLevel.Warning)
        .AddConsole();
        });
        }


        This way you'll only get Warning level logs for logging info starting with the filters passed to builder.AddFilter.



        My log4net.log file now doesn't show that huge amount of INFO logging spit by Microsoft and others.



        More info here @ Microsoft Docs: Log filtering






        share|improve this answer














        What have really worked for me was adding this in ASP.NET Core 2.0 project's Startup.cs file:



        public void ConfigureServices(IServiceCollection services)
        {
        .
        .
        .

        services.AddLogging(
        builder =>
        {
        builder.AddFilter("Microsoft", LogLevel.Warning)
        .AddFilter("System", LogLevel.Warning)
        .AddFilter("NToastNotify", LogLevel.Warning)
        .AddConsole();
        });
        }


        This way you'll only get Warning level logs for logging info starting with the filters passed to builder.AddFilter.



        My log4net.log file now doesn't show that huge amount of INFO logging spit by Microsoft and others.



        More info here @ Microsoft Docs: Log filtering







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jun 15 at 13:00

























        answered Jun 15 at 2:44









        Leniel Maccaferri

        79.4k33287392




        79.4k33287392






















            up vote
            5
            down vote













            In and before ASP.NET 5 RC1 (now ASP.NET Core 1.0), you could do it via the logger factory, i.e.



            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
            // completely disable logging or use one of the other levels, such as Error, Critical, Warning etc.
            loggerFactory.MinimumLevel = LogLevel.None;
            }


            However, with the current branch (not released yet, but available via nightly builds), this has been removed. Now you need to pass the LogLevel per provider. Typically this is done via extension method.



            For the built in console logger, it would be loggerFactory.AddConsole(minimumLevel: LogLevel.Warning); for example.



            Since your logger provider is a custom one, you will have to configure it yourself. Take a look on how the console logger does it. It passes a delegate to the provider, that does the filtering.



            From GitHub Source:



            public static ILoggerFactory AddConsole(
            this ILoggerFactory factory,
            LogLevel minLevel,
            bool includeScopes)
            {
            factory.AddConsole((category, logLevel) => logLevel >= minLevel, includeScopes);
            return factory;
            }


            Of course instead of passing a delegate you can also directly set the log level of log4net.



            Update: To extend on what I've pointed out in the comments



            The ILoggerProvider is only a wrapper around the actual logging framework. In the simple case of ConsoleLoggerProvider, there is no framework as all behind it, just a simple Console.WriteLine call.



            In case of log4net, it's obvious from the example that logging can be enabled on a per level basis. This isn't possible with the .NET Core logger abstraction liked above, as the abstraction doesn't do any filtering.



            In a log4net ILoggerProvider one would simply route all log levels to the log4net net library and have it filter it.



            Based on the linked GitHub issue @haim770 created, you have the SourceContext for filtering and if log4net doesn't have a concept of SourceContext, you'll have to implement this in the provider. If it has a concept of SourceContext, then the provider needs to reroute/translate it into the structure log4net expects it.



            As you can see, the logger itself always stays unaware about internal specifics and implementation details of ASP.NET. The Log4NetProvider can't and shouldn't, because it's task is to translate/wrap around that api. Providers are just abstractions, so we don't have to leak implementation details into a library for example.






            share|improve this answer























            • This is not what I'm after. I do not want to change the logging level globally in my application, I just wish to turn off the ASP.NET logging which is tunneled through my provider. I deep dived into the source code, it's not a trivial task, I'm unhappy :(
              – gdoron
              Feb 7 '16 at 19:31










            • @gdoron: All logging requests will be tunneled to every registered ILoggingProvider. It's the task of the provider/logger to do the log level filtering. That's why MinimumLevel was removed and the now can only be set on per provider level
              – Tseng
              Feb 7 '16 at 19:37










            • I understand that all the loggers should get all logging requests. I just don't understand why there's no way to set ASP.NET itself logging to a specific level, why do I need my logging provider to be aware of all of the components, to me it seems like bad design.
              – gdoron
              Feb 7 '16 at 19:48










            • @gdoron: Because it's the providers responsibility. An application can have more than one provider, setting it globally may make no sense. For example you may have a ConsoleLogger for development, where you want to have all information, including "Trace" and "Debug" Level, on the other side you may want to have file logging which only logs Errors and Criticals. ASP.NET Core is made to be very flexible and be easy to add or remove a certain feature and for that reason. All you need to do is set your logger to Warning Level or higher, then Debug, Information and Trace level won't be logged
              – Tseng
              Feb 7 '16 at 19:52










            • Also your logger provider doesn't need to be aware of any components, just about the debug level, as this is what tells the logger what kind of messages it should log and which not.
              – Tseng
              Feb 7 '16 at 19:53















            up vote
            5
            down vote













            In and before ASP.NET 5 RC1 (now ASP.NET Core 1.0), you could do it via the logger factory, i.e.



            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
            // completely disable logging or use one of the other levels, such as Error, Critical, Warning etc.
            loggerFactory.MinimumLevel = LogLevel.None;
            }


            However, with the current branch (not released yet, but available via nightly builds), this has been removed. Now you need to pass the LogLevel per provider. Typically this is done via extension method.



            For the built in console logger, it would be loggerFactory.AddConsole(minimumLevel: LogLevel.Warning); for example.



            Since your logger provider is a custom one, you will have to configure it yourself. Take a look on how the console logger does it. It passes a delegate to the provider, that does the filtering.



            From GitHub Source:



            public static ILoggerFactory AddConsole(
            this ILoggerFactory factory,
            LogLevel minLevel,
            bool includeScopes)
            {
            factory.AddConsole((category, logLevel) => logLevel >= minLevel, includeScopes);
            return factory;
            }


            Of course instead of passing a delegate you can also directly set the log level of log4net.



            Update: To extend on what I've pointed out in the comments



            The ILoggerProvider is only a wrapper around the actual logging framework. In the simple case of ConsoleLoggerProvider, there is no framework as all behind it, just a simple Console.WriteLine call.



            In case of log4net, it's obvious from the example that logging can be enabled on a per level basis. This isn't possible with the .NET Core logger abstraction liked above, as the abstraction doesn't do any filtering.



            In a log4net ILoggerProvider one would simply route all log levels to the log4net net library and have it filter it.



            Based on the linked GitHub issue @haim770 created, you have the SourceContext for filtering and if log4net doesn't have a concept of SourceContext, you'll have to implement this in the provider. If it has a concept of SourceContext, then the provider needs to reroute/translate it into the structure log4net expects it.



            As you can see, the logger itself always stays unaware about internal specifics and implementation details of ASP.NET. The Log4NetProvider can't and shouldn't, because it's task is to translate/wrap around that api. Providers are just abstractions, so we don't have to leak implementation details into a library for example.






            share|improve this answer























            • This is not what I'm after. I do not want to change the logging level globally in my application, I just wish to turn off the ASP.NET logging which is tunneled through my provider. I deep dived into the source code, it's not a trivial task, I'm unhappy :(
              – gdoron
              Feb 7 '16 at 19:31










            • @gdoron: All logging requests will be tunneled to every registered ILoggingProvider. It's the task of the provider/logger to do the log level filtering. That's why MinimumLevel was removed and the now can only be set on per provider level
              – Tseng
              Feb 7 '16 at 19:37










            • I understand that all the loggers should get all logging requests. I just don't understand why there's no way to set ASP.NET itself logging to a specific level, why do I need my logging provider to be aware of all of the components, to me it seems like bad design.
              – gdoron
              Feb 7 '16 at 19:48










            • @gdoron: Because it's the providers responsibility. An application can have more than one provider, setting it globally may make no sense. For example you may have a ConsoleLogger for development, where you want to have all information, including "Trace" and "Debug" Level, on the other side you may want to have file logging which only logs Errors and Criticals. ASP.NET Core is made to be very flexible and be easy to add or remove a certain feature and for that reason. All you need to do is set your logger to Warning Level or higher, then Debug, Information and Trace level won't be logged
              – Tseng
              Feb 7 '16 at 19:52










            • Also your logger provider doesn't need to be aware of any components, just about the debug level, as this is what tells the logger what kind of messages it should log and which not.
              – Tseng
              Feb 7 '16 at 19:53













            up vote
            5
            down vote










            up vote
            5
            down vote









            In and before ASP.NET 5 RC1 (now ASP.NET Core 1.0), you could do it via the logger factory, i.e.



            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
            // completely disable logging or use one of the other levels, such as Error, Critical, Warning etc.
            loggerFactory.MinimumLevel = LogLevel.None;
            }


            However, with the current branch (not released yet, but available via nightly builds), this has been removed. Now you need to pass the LogLevel per provider. Typically this is done via extension method.



            For the built in console logger, it would be loggerFactory.AddConsole(minimumLevel: LogLevel.Warning); for example.



            Since your logger provider is a custom one, you will have to configure it yourself. Take a look on how the console logger does it. It passes a delegate to the provider, that does the filtering.



            From GitHub Source:



            public static ILoggerFactory AddConsole(
            this ILoggerFactory factory,
            LogLevel minLevel,
            bool includeScopes)
            {
            factory.AddConsole((category, logLevel) => logLevel >= minLevel, includeScopes);
            return factory;
            }


            Of course instead of passing a delegate you can also directly set the log level of log4net.



            Update: To extend on what I've pointed out in the comments



            The ILoggerProvider is only a wrapper around the actual logging framework. In the simple case of ConsoleLoggerProvider, there is no framework as all behind it, just a simple Console.WriteLine call.



            In case of log4net, it's obvious from the example that logging can be enabled on a per level basis. This isn't possible with the .NET Core logger abstraction liked above, as the abstraction doesn't do any filtering.



            In a log4net ILoggerProvider one would simply route all log levels to the log4net net library and have it filter it.



            Based on the linked GitHub issue @haim770 created, you have the SourceContext for filtering and if log4net doesn't have a concept of SourceContext, you'll have to implement this in the provider. If it has a concept of SourceContext, then the provider needs to reroute/translate it into the structure log4net expects it.



            As you can see, the logger itself always stays unaware about internal specifics and implementation details of ASP.NET. The Log4NetProvider can't and shouldn't, because it's task is to translate/wrap around that api. Providers are just abstractions, so we don't have to leak implementation details into a library for example.






            share|improve this answer














            In and before ASP.NET 5 RC1 (now ASP.NET Core 1.0), you could do it via the logger factory, i.e.



            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
            // completely disable logging or use one of the other levels, such as Error, Critical, Warning etc.
            loggerFactory.MinimumLevel = LogLevel.None;
            }


            However, with the current branch (not released yet, but available via nightly builds), this has been removed. Now you need to pass the LogLevel per provider. Typically this is done via extension method.



            For the built in console logger, it would be loggerFactory.AddConsole(minimumLevel: LogLevel.Warning); for example.



            Since your logger provider is a custom one, you will have to configure it yourself. Take a look on how the console logger does it. It passes a delegate to the provider, that does the filtering.



            From GitHub Source:



            public static ILoggerFactory AddConsole(
            this ILoggerFactory factory,
            LogLevel minLevel,
            bool includeScopes)
            {
            factory.AddConsole((category, logLevel) => logLevel >= minLevel, includeScopes);
            return factory;
            }


            Of course instead of passing a delegate you can also directly set the log level of log4net.



            Update: To extend on what I've pointed out in the comments



            The ILoggerProvider is only a wrapper around the actual logging framework. In the simple case of ConsoleLoggerProvider, there is no framework as all behind it, just a simple Console.WriteLine call.



            In case of log4net, it's obvious from the example that logging can be enabled on a per level basis. This isn't possible with the .NET Core logger abstraction liked above, as the abstraction doesn't do any filtering.



            In a log4net ILoggerProvider one would simply route all log levels to the log4net net library and have it filter it.



            Based on the linked GitHub issue @haim770 created, you have the SourceContext for filtering and if log4net doesn't have a concept of SourceContext, you'll have to implement this in the provider. If it has a concept of SourceContext, then the provider needs to reroute/translate it into the structure log4net expects it.



            As you can see, the logger itself always stays unaware about internal specifics and implementation details of ASP.NET. The Log4NetProvider can't and shouldn't, because it's task is to translate/wrap around that api. Providers are just abstractions, so we don't have to leak implementation details into a library for example.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 8 '16 at 8:38

























            answered Feb 7 '16 at 16:27









            Tseng

            32.5k585117




            32.5k585117












            • This is not what I'm after. I do not want to change the logging level globally in my application, I just wish to turn off the ASP.NET logging which is tunneled through my provider. I deep dived into the source code, it's not a trivial task, I'm unhappy :(
              – gdoron
              Feb 7 '16 at 19:31










            • @gdoron: All logging requests will be tunneled to every registered ILoggingProvider. It's the task of the provider/logger to do the log level filtering. That's why MinimumLevel was removed and the now can only be set on per provider level
              – Tseng
              Feb 7 '16 at 19:37










            • I understand that all the loggers should get all logging requests. I just don't understand why there's no way to set ASP.NET itself logging to a specific level, why do I need my logging provider to be aware of all of the components, to me it seems like bad design.
              – gdoron
              Feb 7 '16 at 19:48










            • @gdoron: Because it's the providers responsibility. An application can have more than one provider, setting it globally may make no sense. For example you may have a ConsoleLogger for development, where you want to have all information, including "Trace" and "Debug" Level, on the other side you may want to have file logging which only logs Errors and Criticals. ASP.NET Core is made to be very flexible and be easy to add or remove a certain feature and for that reason. All you need to do is set your logger to Warning Level or higher, then Debug, Information and Trace level won't be logged
              – Tseng
              Feb 7 '16 at 19:52










            • Also your logger provider doesn't need to be aware of any components, just about the debug level, as this is what tells the logger what kind of messages it should log and which not.
              – Tseng
              Feb 7 '16 at 19:53


















            • This is not what I'm after. I do not want to change the logging level globally in my application, I just wish to turn off the ASP.NET logging which is tunneled through my provider. I deep dived into the source code, it's not a trivial task, I'm unhappy :(
              – gdoron
              Feb 7 '16 at 19:31










            • @gdoron: All logging requests will be tunneled to every registered ILoggingProvider. It's the task of the provider/logger to do the log level filtering. That's why MinimumLevel was removed and the now can only be set on per provider level
              – Tseng
              Feb 7 '16 at 19:37










            • I understand that all the loggers should get all logging requests. I just don't understand why there's no way to set ASP.NET itself logging to a specific level, why do I need my logging provider to be aware of all of the components, to me it seems like bad design.
              – gdoron
              Feb 7 '16 at 19:48










            • @gdoron: Because it's the providers responsibility. An application can have more than one provider, setting it globally may make no sense. For example you may have a ConsoleLogger for development, where you want to have all information, including "Trace" and "Debug" Level, on the other side you may want to have file logging which only logs Errors and Criticals. ASP.NET Core is made to be very flexible and be easy to add or remove a certain feature and for that reason. All you need to do is set your logger to Warning Level or higher, then Debug, Information and Trace level won't be logged
              – Tseng
              Feb 7 '16 at 19:52










            • Also your logger provider doesn't need to be aware of any components, just about the debug level, as this is what tells the logger what kind of messages it should log and which not.
              – Tseng
              Feb 7 '16 at 19:53
















            This is not what I'm after. I do not want to change the logging level globally in my application, I just wish to turn off the ASP.NET logging which is tunneled through my provider. I deep dived into the source code, it's not a trivial task, I'm unhappy :(
            – gdoron
            Feb 7 '16 at 19:31




            This is not what I'm after. I do not want to change the logging level globally in my application, I just wish to turn off the ASP.NET logging which is tunneled through my provider. I deep dived into the source code, it's not a trivial task, I'm unhappy :(
            – gdoron
            Feb 7 '16 at 19:31












            @gdoron: All logging requests will be tunneled to every registered ILoggingProvider. It's the task of the provider/logger to do the log level filtering. That's why MinimumLevel was removed and the now can only be set on per provider level
            – Tseng
            Feb 7 '16 at 19:37




            @gdoron: All logging requests will be tunneled to every registered ILoggingProvider. It's the task of the provider/logger to do the log level filtering. That's why MinimumLevel was removed and the now can only be set on per provider level
            – Tseng
            Feb 7 '16 at 19:37












            I understand that all the loggers should get all logging requests. I just don't understand why there's no way to set ASP.NET itself logging to a specific level, why do I need my logging provider to be aware of all of the components, to me it seems like bad design.
            – gdoron
            Feb 7 '16 at 19:48




            I understand that all the loggers should get all logging requests. I just don't understand why there's no way to set ASP.NET itself logging to a specific level, why do I need my logging provider to be aware of all of the components, to me it seems like bad design.
            – gdoron
            Feb 7 '16 at 19:48












            @gdoron: Because it's the providers responsibility. An application can have more than one provider, setting it globally may make no sense. For example you may have a ConsoleLogger for development, where you want to have all information, including "Trace" and "Debug" Level, on the other side you may want to have file logging which only logs Errors and Criticals. ASP.NET Core is made to be very flexible and be easy to add or remove a certain feature and for that reason. All you need to do is set your logger to Warning Level or higher, then Debug, Information and Trace level won't be logged
            – Tseng
            Feb 7 '16 at 19:52




            @gdoron: Because it's the providers responsibility. An application can have more than one provider, setting it globally may make no sense. For example you may have a ConsoleLogger for development, where you want to have all information, including "Trace" and "Debug" Level, on the other side you may want to have file logging which only logs Errors and Criticals. ASP.NET Core is made to be very flexible and be easy to add or remove a certain feature and for that reason. All you need to do is set your logger to Warning Level or higher, then Debug, Information and Trace level won't be logged
            – Tseng
            Feb 7 '16 at 19:52












            Also your logger provider doesn't need to be aware of any components, just about the debug level, as this is what tells the logger what kind of messages it should log and which not.
            – Tseng
            Feb 7 '16 at 19:53




            Also your logger provider doesn't need to be aware of any components, just about the debug level, as this is what tells the logger what kind of messages it should log and which not.
            – Tseng
            Feb 7 '16 at 19:53


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35251078%2fhow-to-turn-off-the-logging-done-by-the-asp-net-core-framework%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

            How to change which sound is reproduced for terminal bell?

            Can I use Tabulator js library in my java Spring + Thymeleaf project?