1

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 :)

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
  • Have you looked at [Creating a dynamic logger?](http://stackoverflow.com/q/2648168/724591) What you want to do I don't believe can be accomplished by one Logger. – matth Feb 14 '14 at 16:42
  • I've just tried it and it looks promising! I'll run some tests tomorrow.. – user3309364 Feb 18 '14 at 18:26
  • Really fun peace of code and cool stuff to work with! I'm still wondering why I couldn't get the original solution to work. Log4net gives us the possibility to set a property in a threat context.. For me, this functionality suggests that my original solution should be possible.. somehow. – user3309364 Feb 18 '14 at 18:37

0 Answers0