开发者

Thread Safety of log4net

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 exampl开发者_如何学Pythone of lets say RollingFileAppender used in a thread-safe way? does it need to be pushed into context? somehow locked, or what?


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!");
}


Straight from the log4net FAQ:

Is log4net thread-safe?

Yes, log4net is thread-safe.

So, no need for manual locking.


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.


Thread Safety of log4net

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜