删除 ThreadContext 属性

发布于 2024-12-07 17:39:46 字数 329 浏览 0 评论 0原文

我已经设置了 ThreadContext.Properties,并且需要在代码的生命周期中更新其值。过去我使用过 log4j MDC 并且必须: MDC.删除(跟踪);

然后通过以下方式添加另一个值: MDC.put(跟踪,trackingIdStr);

现在我正在使用 Log4Net,我们的应用程序使用属性: log4net.ThreadContext.Properties["TrackingId"] = tracker;

问题:如何删除以前的值并添加新值?是不是很简单: log4net.ThreadContext.Properties["TrackingId"] = tracker2;

I have set the ThreadContext.Properties and need to update its value during the life-cycle of my code. In the past I have used log4j MDC and had to:
MDC.remove(TRACKING);

and then add another value by:
MDC.put(TRACKING, trackingIdStr);

Now that I am using Log4Net, our app uses Properties:
log4net.ThreadContext.Properties["TrackingId"] = tracker;

Question: How do I remove the previous value and add a new value? Is it as easy as just:
log4net.ThreadContext.Properties["TrackingId"] = tracker2;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼眸里的那抹悲凉 2024-12-14 17:39:46

是的,就是这么简单。  您可以按照问题中所示重新分配,也可以在完成后完全删除该值。

//set
ThreadContext.Properties["TrackingId"] = tracker1;

//reset
ThreadContext.Properties["TrackingId"] = tracker2;

//completely remove
ThreadContext.Properties.Remove("TrackingId");

如果您希望上下文属性对特定代码段有效(通过使用),那么您可以尝试 ThreadContext.Stacks:

using(ThreadContext.Stacks["TrackingId"].Push("hello"))
{
  //messages logged here will be tagged with TrackingId="hello"
}
//messages logged here will not be tagged with TrackingId="hello"

Yes, it is that easy.  You can reassign as you have shown in your question or you can remove the value altogether when you are finished with it. 

//set
ThreadContext.Properties["TrackingId"] = tracker1;

//reset
ThreadContext.Properties["TrackingId"] = tracker2;

//completely remove
ThreadContext.Properties.Remove("TrackingId");

If you want your context properties to be in effect for a specific section of code (via using) then you can try ThreadContext.Stacks:

using(ThreadContext.Stacks["TrackingId"].Push("hello"))
{
  //messages logged here will be tagged with TrackingId="hello"
}
//messages logged here will not be tagged with TrackingId="hello"
北凤男飞 2024-12-14 17:39:46

也许这并不能直接回答您的问题,但在您的情况下,您可能会考虑使用计算出的上下文值。这里有很好的解释:

Log4Net 教程第 6 部分:记录事件上下文

(向下滚动一点)

Maybe this does not directly answer your question, but in your situation you might consider to use calculated context values. This is explained nicely here:

Log4Net Tutorial pt 6: Log Event Context

(scroll down a bit)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文