Log4Net config in external file does not work

We are using log4net and want to specify it's configuration in an external config file (as we have done with other sections). To do this we have changed the log4net section in the App.config to:

...
<section name="log4net" 
     type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
...
<log4net configSource="Log.config" />
...

And in the Log.Config file (same directory as the App.config) we have:

<log4net>
  <appender name="General" type="log4net.Appender.FileAppender">
    <file value="myapp.log" />
    <layout type="log4net.Layout.SimpleLayout" />
  </appender>
  <root>
    <appender-ref ref="General" />
  </root>
</log4net>

However, when we run the app, no log file is created (and no logging done). There are no error messages output to the console.

If we move the contents of the Log.config file back into the App.config (replacing the first code line above), it works as expected. Any idea why it is not working in an external file?


Do you have the following attribute in your AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

and code like this at the start of each class that requires logging functionality:

private static readonly ILog log = 
LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

I have a blog post containing this and other info here.


There is an open defect on this issue. Log4Net does not support the configSource attribute of configuration elements. To use a purely configuration file solution you use the log4net.Config key in appSettings.

Step 1: Include the normal configuration section definition:

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>

Step 2: Use the magic log4net.Config key in appSettings.

<appSettings>
      <add key="log4net.Config" value="log4net.simple.config" />
</appSettings>

Step 3: Contribute a patch to fix the handling of configSource.


The step that has been missed is

log4net.Config.XmlConfigurator.Configure(); 

this will cause the configSource to be used. Make sure you call it once before calling GetLogger();


Make sure that your log4net.config file is set with the following properties:

Build Action: Content

Copy to output directory: Copy Always


Either use,

<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<appSettings>
<add key="log4net.Config" value="Log4Net.config" />
</appSettings>

or just,

log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo("Log4Net.config"));

In both cases the file,Log4Net.config, should be there in output directory. You can do this by setting Log4Net.config file properties in solution explorer. Build Action - Content and Copy to Output Directory - Copy always