-->

对于在并行编程log4net的记录动态文件名(Dynamic filename for loggin

2019-10-19 08:06发布

Here is the scenario:
I have some 'messages' (data) that has to be processed in parallel.
In these parallel processes, I would like to log some things in a message specific logfile.
I've tried many things, but my logs just get messed up.

I've written a small test project.. Let's see the code:

using System.Collections.Generic;
using System.Threading.Tasks;

namespace ParallelTest
{
    public class MessageController
    {
       public void InitiateProcesses(List<Message> messagesToProces)
       {
          MessageProcessor messageProcessor = new MessageProcessor();
          Parallel.ForEach(messagesToProces, messageProcessor.ProcessMessage);
       }
    }
}

The MessageProcessor looks like this:

using log4net;

namespace ParallelTest
{
    public class MessageProcessor
    {
        public void ProcessMessage(Message message)
        {
            log4net.ThreadContext.Properties["LogName"] = message.MessageId;
            ILog log = LogManager.GetLogger("CsvLogger");
            log4net.Config.XmlConfigurator.Configure();
            log.Info(string.Format("{0} - {1}", message.MessageId, message.Body));
        }
    }
}

So I'm using log4net and this is the configuration:

<log4net>
  <appender name="CsvAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="c:\Temp\log_%property{LogName}.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="-1" />
    <maximumFileSize value="1MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date,%message%newline" />
    </layout>
  </appender>

  <logger additivity="false" name="CsvLogger">
    <level value="ALL"/>
    <appender-ref ref="CsvAppender" />
  </logger>
</log4net>

The logfiles are created, but..

  • Some of them are empty
  • Some of them are filled with the correct message logging
  • Some of them also contains logging of other messages

I could use some help here :)

文章来源: Dynamic filename for logging with log4net in parallel programming