How to track down log4net problems

I use log4net all the time, but one thing I've never figured out is how to tell what's going on on the inside. For example, I've got a console appender and a database appender in my project. I made a few changes to the database and the code, and now the database appender doesn't work anymore. I'll figure out why eventually, but it would help a lot if I could see what's going on inside log4net.

Does log4net generate any kind of output that I can view to try to determine the source of my problem?


Solution 1:

First you have to set this value on the application configuration file:

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

Then, to determine the file in which you want to save the output you can add the following code in the same .config file:

<configuration>
...

<system.diagnostics>
    <trace autoflush="true">
        <listeners>
            <add 
                name="textWriterTraceListener" 
                type="System.Diagnostics.TextWriterTraceListener" 
                initializeData="C:\tmp\log4net.txt" />
        </listeners>
    </trace>
</system.diagnostics>

...
</configuration>

You can find a more detailed explanation under 'How do I enable log4net internal debugging?' in the log4net FAQ page.

Solution 2:

If you are using a log4net config file you can also turn on the debugging there by changing the top node to:

<log4net debug="true">

This will work once the config is reloaded and assuming your trace listener is setup properly.

Solution 3:

In addition to the above answer, you can use this line to see the log in realtime instead of the c:\tmp\log4net.txt output.

log4net.Util.LogLog.InternalDebugging = true;

For example, in a console app, you can add this and then watch the output in realtime. It's good for debugging log4net in a small test harness to see what's happening with the appender you're testing.

Solution 4:

Make sure the root application where your entry point is logs something to log4net. Give it one of these:

private static ILog logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
    logger.InfoFormat("{0} v.{1} started.", Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString());

With 2.0.8, I had an interesting situation. I created a library project and a test exe project that would demo it's capabilities. The library project was set up to use Log4net as was the exe project. The exe project used the assemblyinfo attribute to register the config, yet I was getting no logging output to either the console or the log file. When I turned on log4net internal debug logging, I got some internal messages written to the console, but still none of my normal logs. No errors were being reported. It all started working when I added the above code to my program. Log4net was otherwise setup correctly.