23

There seems to be some discussion on whether log4net is thread-safe, the consensus is that the framework is thread-safe, but appenders are not and need to be used correctly to achieve thread-safety. can someone shine some light on this and possibly give example of lets say RollingFileAppender used in a thread-safe way? does it need to be pushed into context? somehow locked, or what?

4 Answers 4

28

According to this link, RollingFileAppender is thread safe (as far as logging is concerned). This is coming from one of the developers of log4net. He specifically says that locking like this is not required in your code:

lock(logger)
{
  logger.Info("Hello!");
}
0
11

Straight from the log4net FAQ:

Is log4net thread-safe?

Yes, log4net is thread-safe.

So, no need for manual locking.

1
1

But I've had a deadlock with ColoredConsoleAppender. And it sources comment states that internal writer (m_consoleOutputWriter) is not thread safe!

/// <summary>
/// The console output stream writer to write to
/// </summary>
/// <remarks>
/// <para>
/// This writer is not thread safe.
/// </para>
/// </remarks>
private System.IO.StreamWriter m_consoleOutputWriter = null;

And I've switched back to basic ConsoleAppender and have no issues since then.

0
0

enter image description here

I have two appenders in my config, one of which is Console Appender, and I see it locking up very consistently:

PatternLayout consoleLayout = new PatternLayout("%date{HH:mm:ss,fff} [%thread] %-5level %logger – %message%newline");
        var consoleApender = new ConsoleAppender();
        consoleApender.Layout = consoleLayout;
        
        hierarchy.Root.AddAppender(consoleApender);

        PatternLayout fileLayout = new PatternLayout("%date{yyyy.MM.dd HH:mm: ss,fff} [%thread] %-5level %logger – %message%newline");
        RollingFileAppender rollingFileAppender = new RollingFileAppender();
        rollingFileAppender.AppendToFile = false;
        rollingFileAppender.File = "NetAutomationLog." + DateTime.Now.ToString("yy.MM.dd.HH.mm.ss") + ".log"; 
        rollingFileAppender.Layout = fileLayout;
        rollingFileAppender.MaxSizeRollBackups = 5;
        rollingFileAppender.MaximumFileSize = "20MB";
        rollingFileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
        rollingFileAppender.StaticLogFileName = true;
        rollingFileAppender.ActivateOptions();

        hierarchy.Root.AddAppender(rollingFileAppender);

        hierarchy.Root.Level = Level.Debug;
        hierarchy.Configured = true;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.