views:

1139

answers:

2

We have an application that runs in multiple threads and uses Log4Net as logging framework. We encountered a scenario where some log events weren't logged. As mentioned in the docs, the FileAppender and the other Appenders are "not safe for multithreaded operations". I searched the web for solutions or Appenders, but couldn't find any.
Do you know a multithread safe Log4Net Appender that uses a ring buffer or a queue to provide multithread support? Or should we use a different multithread safe logging framework at all?
Thanks in advance!

+4  A: 

I've never used FileAppender and cannot say if it is thread safe but I have never had any problems with RollingFileAppender. The docs state that members of the type are not thread safe, but this should be OK unless you try to directly write to the appender. You do not need to add your own locking code around calls like:

log.Info("message");
Darin Dimitrov
Yes, log4net automatically locks log calls so there is no threading problem here.
Julien Lebosquain
So you're saying that Log4Net is multithread safe if it's used through the Logger API? So I guess there has to be problem in our code that's using it?<br>In each class we are creating a logger like this:<pre><code>private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);</code></pre><br>But only one instance of this class is used in a thread.
Rene Schulte
+2  A: 

I wrote some Unit tests to reproduce the problem: A test creates 50 threads and each thread logs 500 messages. Afterwards the written lines were counted and as a result I got 25,000 (50 x 500) lines in different order. I tested it on a dual core and on a eight core machine.
I tested a static Logger:

private static ILog StaticLog = log4net.LogManager.GetLogger(RepositoryName, "Static logger");

and with a Logger for each instance of the test class / thread:

ILog instanceLog = LogManager.GetLogger(RepositoryName, "Instance logger: " + ThreadId.ToString());


And all tests were green.

So Log4Net works fine and handles multithreading scenarios well. The Appender docs should be updated and state that multithreaded operations are supported if the Logger API is used in the right way.

I guess the problem with missing log entries that we encountered on a customer's machine is caused by other issues. Maybe the underlying VM or hardware is broken.

Thanks for your help!

Rene Schulte