为什么log4net线程会等待?

上周,我们的一个测试服务器用完了日志驱动器上的磁盘空间 . 在释放磁盘空间后,我仍然有几个带调用堆栈的线程似乎被卡在log4net AppenderSkeleton.DoAppend中,这让我感到困惑,因为我期望log4net是线程安全的 .

  • 我是否正确看到线程被卡住了?

  • 堆栈是否表示线程卡在'lock(this)'或其他地方?我的猜测在其他地方,因为我希望看到像Monitor.Enter这样的东西,如果它被锁定(这个) .

  • 其中一个主题似乎在翻转到新文件的过程中显示DoAppend . 是否可以在创建此文件时阻止所有DoAppend线程?但是,我希望在释放磁盘空间后,这些线程会被解除阻塞 .

Any help understanding why log4net seems to be stuck across so many threads is appreciated.

下面是一个示例调用堆栈,显示在DoAppend内等待时阻塞的线程:

ntdll.dll!_NtWaitForMultipleObjects@20()0x15字节ntdll.dll!_NtWaitForMultipleObjects@20()0x15字节KERNELBASE.dll!_WaitForMultipleObjectsEx@20()0x36字节kernel32.dll!_WaitForMultipleObjectsExImplementation@20()0x8e字节[管理到本机转换] log4net.dll!log4net.Appender.AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent loggingEvent)0x3e bytes log4net.dll!log4net.Util.AppenderAttachedImpl.AppendLoopOnAppenders(log4net.Core.LoggingEvent loggingEvent)0xa0 bytes log4net.dll!log4net.Repository .Hierarchy.Logger.CallAppenders(log4net.Core.LoggingEvent loggingEvent)0xa9 bytes log4net.dll!log4net.Repository.Hierarchy.Logger.ForcedLog(System.Type callerStackBoundaryDeclaringType,log4net.Core.Level level,object message,System.Exception exception) 0x4a bytes log4net.dll!log4net.Repository.Hierarchy.Logger.Log(System.Type callerStackBoundaryDeclaringType,log4net.Core.Level level,object message,System.Exception exception)0x5e bytes log4net.dll!log4n et.Core.LogImpl.Info(对象消息)0x27字节

这是log4net AppenderSkeleton.DoAppend的源代码

public void DoAppend(LoggingEvent loggingEvent) 
{
    // This lock is absolutely critical for correct formatting
    // of the message in a multi-threaded environment.  Without
    // this, the message may be broken up into elements from
    // multiple thread contexts (like get the wrong thread ID).

    lock(this)
    {
        if (m_closed)
        {
            ErrorHandler.Error("Attempted to append to closed appender named ["+m_name+"].");
            return;
        }

        // prevent re-entry
        if (m_recursiveGuard)
        {
            return;
        }

        try
        {
            m_recursiveGuard = true;

            if (FilterEvent(loggingEvent) && PreAppendCheck())
            {
                this.Append(loggingEvent);
            }
        }
        catch(Exception ex)
        {
            ErrorHandler.Error("Failed in DoAppend", ex);
        }
#if !MONO && !NET_2_0
        // on .NET 2.0 (and higher) and Mono (all profiles), 
        // exceptions that do not derive from System.Exception will be
        // wrapped in a RuntimeWrappedException by the runtime, and as
        // such will be catched by the catch clause above
        catch
        {
            // Catch handler for non System.Exception types
            ErrorHandler.Error("Failed in DoAppend (unknown exception)");
        }
#endif
        finally
        {
            m_recursiveGuard = false;
        }
    }
}

这是我的log4net设置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net xsi:noNamespaceSchemaLocation="log4net.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="g:\logfiles\mySerivceName\" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value="'myServiceName.'yyyy-MM-dd-HH'-00.log'"/>
      <staticLogFileName value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss.fff} %-5level [%3thread] [%-50.50stacktrace] %message %newline"/>
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="INFO" />
        <levelMax value="FATAL" />
      </filter>
    </appender>
    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
        <to value="alerts@myCompanyName.com" />
        <from value="servicename@localnetwork" />
        <subject value="${COMPUTERNAME} - Error Generated" />
        <smtpHost value="mySmtpServerIpAddress" />
        <bufferSize value="2" />
        <lossy value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss.fff} %-5level [%3thread] [%-50.50stacktrace] %message %newline" />
        </layout>
        <filter type="log4net.Filter.LevelRangeFilter">
            <levelMin value="ERROR" />
            <levelMax value="FATAL" />
        </filter>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>
</configuration>

The DoAppend stack that is rolling over to a new file

mscorlib.dll!System.Text.StringBuilder.Append(char value)第953行0xb字节
mscorlib.dll!System.IO.PathHelper.Append(char value)第139行0x18字节
mscorlib.dll!System.IO.Path.NormalizePath(string path,bool fullCheck,int maxPathLength,bool expandShortPaths)620行
mscorlib.dll!System.IO.Path.GetDirectoryName(字符串路径)第170行0x24字节
log4net.dll!log4net.Appender.FileAppender.LockingModelBase.CreateStream(string filename,bool append,System.IO.FileShare fileShare)0x35 bytes
log4net.dll!log4net.Appender.FileAppender.ExclusiveLock.OpenFile(string filename,bool append,System.Text.Encoding encoding)0x2d bytes
log4net.dll!log4net.Appender.FileAppender.OpenFile(string fileName,bool append)0x1ac bytes
log4net.dll!log4net.Appender.RollingFileAppender.OpenFile(string fileName,bool append)0x189 bytes
log4net.dll!log4net.Appender.FileAppender.SafeOpenFile(string fileName,bool append)0x2d bytes
log4net.dll!log4net.Appender.FileAppender.PrepareWriter()0x13字节
log4net.dll!log4net.Appender.TextWriterAppender.PreAppendCheck()0x32字节
log4net.dll!log4net.Appender.AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent loggingEvent)0xe0 bytes
log4net.dll!log4net.Util.AppenderAttachedImpl.AppendLoopOnAppenders(log4net.Core.LoggingEvent loggingEvent)0xa0 bytes
log4net.dll!log4net.Repository.Hierarchy.Logger.CallAppenders(log4net.Core.LoggingEvent loggingEvent)0xa9 bytes
log4net.dll!log4net.Repository.Hierarchy.Logger.ForcedLog(System.Type callerStackBoundaryDeclaringType,log4net.Core.Level level,object message,System.Exception exception)0x4a bytes
log4net.dll!log4net.Repository.Hierarchy.Logger.Log(System.Type callerStackBoundaryDeclaringType,log4net.Core.Level level,object message,System.Exception exception)0x5e bytes
log4net.dll!log4net.Core.LogImpl.Info(对象消息)0x27字节

这是同一台机器上的另一个调用堆栈,不同的进程,也挂起:

clr.dll!AwareLock :: Contention()0x10d bytes [管理到本机转换] log4net.dll!log4net.Appender.AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent loggingEvent)0x3e bytes log4net.dll!log4net.Util.AppenderAttachedImpl . AppendLoopOnAppenders(log4net.Core.LoggingEvent loggingEvent)0xa0字节log4net.dll!log4net.Repository.Hierarchy.Logger.CallAppenders(log4net.Core.LoggingEvent loggingEvent)0xa9 bytes log4net.dll!log4net.Repository.Hierarchy.Logger.ForcedLog(System.Type callerStackBoundaryDeclaringType,log4net.Core.Level level,object消息,System.Exception异常)0x4a bytes log4net.dll!log4net.Repository.Hierarchy.Logger.Log(System.Type callerStackBoundaryDeclaringType,log4net.Core.Level level,object message,System.Exception exception)0x5e bytes log4net.dll!log4net .Core.LogImpl.Info(对象消息)0x27字节

在同一台机器上的第二个进程中,还有一个线程似乎被阻止尝试翻转 .

MSVCR120_CLR0400.dll!_memcpy()0x21e bytes [管理到本机转换] mscorlib.dll!System.Buffer._Memcpy(byte * dest,byte * src,int len)行484 0x20字节C#mscorlib.dll!System.Buffer . Memcpy(byte * dest,byte * src,int len)第401行C#mscorlib.dll!string.FillStringChecked(string dest,int destPos,string src)第1523行0xf字节C#mscorlib.dll!string.ConcatArray(string [] values ,int totalLength)第3340行C#mscorlib.dll!string.Concat(object [] args)第3180行0xa字节C#log4net.dll!log4net.Appender.FileAppender.OpenFile(字符串fileName,bool追加)0x162字节log4net.dll!log4net .Appender.RollingFileAppender.OpenFile(string fileName,bool append)0x189 bytes log4net.dll!log4net.Appender.FileAppender.SafeOpenFile(string fileName,bool append)0x2d bytes log4net.dll!log4net.Appender.FileAppender.PrepareWriter()0x13 bytes log4net.dll!log4net.Appender.TextWriterAppender.PreAppendCheck()0x32 bytes log4net.dll!log4net.Appender.AppenderSkeleton.DoAppend(log4ne t.Core.LoggingEvent loggingEvent)0xe0 bytes log4net.dll!log4net.Util.AppenderAttachedImpl.AppendLoopOnAppenders(log4net.Core.LoggingEvent loggingEvent)0xa0 bytes log4net.dll!log4net.Repository.Hierarchy.Logger.CallAppenders(log4net.Core.LoggingEvent loggingEvent )0xa9 bytes log4net.dll!log4net.Repository.Hierarchy.Logger.ForcedLog(System.Type callerStackBoundaryDeclaringType,log4net.Core.Level level,object message,System.Exception exception)0x4a bytes log4net.dll!log4net.Repository.Hierarchy.Logger .Log(System.Type callerStackBoundaryDeclaringType,log4net.Core.Level level,object message,System.Exception exception)0x5e bytes log4net.dll!log4net.Core.LogImpl.Info(object message)0x27 bytes

回答(1)

3 years ago

我在堆栈溢出时多次看到log4net的这种行为 . 当磁盘空间不足时,fileappender似乎开始阻塞 . 我想这是appender中的一个错误,所以将此作为bug记录似乎适合这种情况 .