Wednesday, July 27, 2011

Finding log4net hidden exceptions....


Recently I worked on a project that was mainly a couple of Web Services, and included a couple of more C# class libraries (e.g : a Data Access Layer, Common project with general utilities, etc..).

In the web services code, we had a lot of calls to our logging utility, which in this case used log4net. I had previous experience using log4net, so I knew (or thought i knew!) how to set it up quickly. I added what I needed in the web.config file, and thought it was enough.

Once I started testing the web services out, I realized that something was wrong with the log4net configuration. The problem was that it wasn't writing anything to any log file whatsoever. The bigger problem was that we didn't know why!?!...
log4net doesn't throw any exceptions if it doesn't work, and this way it doesn't interfere with your running application if, lets say, the log file it should write to has been deleted or is locked by another application for some reason...

However, log4net will write to a trace file, if you set one up...
This led me to the solution of my problem. All I did, was add a TextWriterTraceListener in my web.config, without even altering any code, and the log4net error was immediately written to my trace file.

In my case, I forgot to tell log4net to use Xml Configuration, but this is irrelevant. The point is that this might help you find out what your error is in the case of misconfiguration with log4net...

To set up a trace file through log4net, just add :

    
        
            
                
                
            
        
    

to your web.config file.

Trace listeners are a powerful tool when used wisely :)
You can read more about them here : MSDN - Trace Listeners

Happy Tracing...