Conflict between Log4Net ThreadContext and Task

Has anyone tried to drain contexts and use tasks at the same time?

I am trying something like this:

using (log4net.ThreadContext.Stacks["contextLog"].Push("Saving Data")) { log.Info("Starting transaction"); var taskList = new List<Task>(); taskList.Add(Task.Factory.StartNew(() => { log.Info("Inside Transaction"); })); Task.WaitAll(taskList.ToArray()); } 

and I get this result:

 2015/42/26 13:42:10,841 INFO [Saving Data] Starting transaction 2015/42/26 13:42:10,870 INFO [(null)] Inside Transaction 

I expected it to be [Saving Data] instead of [(null)] in the second line.

It looks like it will lose access to the ThreadContext log4net stack as soon as it starts a new task.

Do you know how to avoid this?

EDIT: At first, the thought was a problem with the transaction scope, but as @stuartd pointed out to me, it worked fine. Then I realized that there was a problem, and it was a real problem.

+5
source share
1 answer

The task will be executed in another thread, so the data in the ThreadContext stack is not available, instead use log4net.LogicalThreadContext as data that should follow the logical execution and still be visible to the Task

+4
source

All Articles