Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conflict between Log4Net's ThreadContext and Task

Has anyone tried to stack contexts and use Tasks at the same time?

I'm 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'm getting that 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 was expecting it to have [Saving Data] instead of [(null)] on the second line.

It appears to lose access to the log4net ThreadContext Stack as soon as it starts a new Task.

Do you know how to avoid this?

EDIT: At first o thought is was a problem with Transaction Scope, but as @stuartd pointed me, it was working fine. Then I realized that there was a task and that was the real problem.

like image 823
Ílson Bolzan Avatar asked Sep 27 '22 22:09

Ílson Bolzan


1 Answers

The task will run on a different thread so the data in the ThreadContext stack isn't available, you should use the log4net.LogicalThreadContext instead as data in that should follow the logical execution and still be visible to the Task

like image 115
Trevor Pilley Avatar answered Sep 30 '22 05:09

Trevor Pilley