Thursday, November 6, 2008

How to switch on log4net internal logging

If you want log4net to show its own internal logging, which is useful to find out where it is looking for your XML configuration file, you can add the following XML to your app.config file:

<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>

Note that if you are using log4net in a DLL, this goes into the app.config file for the EXE that is calling your DLL.

Monday, November 3, 2008

Log4Net using a named config file

Setting up Log4Net with your configuration in the app.config file is pretty straight-forward to do - a quick Google will lead to a number of posts on how to do this.

But if you decide to move your log4net config settings to an external file (convention seems to be "log4net.config") then there are a few misconceptions floating around. There are only two further steps you need to take to achieve this:

1. Copy the <log4net> ... </log4net> section out of your app.config and save it into a new file called log4net.config. You should totally remove it from the app.config file once you feel confident - it is no longer needed.

2. Modify your AssembyInfo.cs file by removing this:

[assembly: log4net.Config.XmlConfigurator
(Watch = true)]


and replacing it with this:

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


Now if you fire up the IDE and run it, your logging should still work. If you don't see any logging, then check that the log4net.config is in the current application path - if you are running from the IDE then that will be where the EXE lives at "../MyProject/bin/Debug/". If you've placed the log4net.config file in your project home folder then you can get it working through the IDE with this:

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


Note that this will need to be reviewed come deployment time!

OR, even better, just select the config file in the IDE and, in the Properties window, change the "Copy to Output Directory" value to "Copy always". Now when you build it through the IDE it will follow your compiled file around. Nice!

Note that you do NOT need to add log4net.Config.XmlConfigurator.Configure() or log4net.Config.XmlConfigurator.Configure({file name}) to the code in your project! This does a manual configuration which overrides what is in the AssemblyInfo.cs file. If you get the AssemblyInfo.cs parameters right then that is all you need.