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:\\Users\\xxxx xxxx\\AppData\\L
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 _sourceFilterFunc;
private readonly ConcurrentDictionary _loggers = new ConcurrentDictionary();
public Log4NetProvider(Func 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
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 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."));
}