NLog中MappedDiagnosticsLogicalContext的问题

时间:2016-02-16 08:53:57

标签: nlog

我使用MappedDiagnosticsLogicalContext,因为我需要数据在异步调用中流动。这是我的NLog.config:

<column name="UserId" layout="${mdlc:item=UserId}" />

但在某些情况下我需要禁用流动,而我不知道该怎么做。例如,我有创建多个线程的代码(请参阅注释):

void Run()
{
    logger.Info("Starting threads...");  // MappedDiagnosticsLogicalContext.LogicalThreadDictionary is called and ConcurrentDictionary is created

    (new Thread(Func1)).Start();  // both threads will refer to the same ConcurrentDictionary object and share common values, because MappedDiagnosticsLogicalContext stores data in logical call context
    (new Thread(Func2)).Start();
}

void Func1()
{
    MappedDiagnosticsLogicalContext.Set("UserId", "123");
    logger.Info("Some message for Func1");
}

void Func2()
{
    Thread.Sleep(5000);
    logger.Info("Some message for Func2");  // UserId will be added to the log message here (because it was added in other thread), but I don't need it
}

我找到了脏的解决方法:在Func2()的开头,我打电话给

CallContext.FreeNamedDataSlot("NLog.AsyncableMappedDiagnosticsContext")

因此,当在Func2()中进行日志记录时,属性MappedDiagnosticsLogicalContext.LogicalThreadDictionary的getter将创建新的ConcurrentDictionary,并且线程将具有单独的字典实例。在MappedDiagnosticsLogicalContext类中使用这样的功能会很好。还是有其他方法可以解决问题吗?

1 个答案:

答案 0 :(得分:2)

在NLog 4.3中,将添加MappedDiagnosticsLogicalContext.Clear(bool freeDataslot),请参阅commit

但在这种情况下使用MDC(而不是MDLC)是不是有意义?