问题描述
来自此答案 https://stackoverflow.com/a/a/a/25125159/4367326 我想为程序中的每个线程设置ThreadContext.
当我设置
时ThreadContext.put("logFileName", "TestLogFile");
它适用于预期的主线程和日志,但对我的应用程序中的任何其他线程都不适.我该如何实现?
推荐答案
如果您设置了系统属性 isthreadContextmapinableable ,则每个子线程将继承父亲threadContext状态.但这对执行者不起作用,因此您需要手动将数据从一个线程复制到另一个线程.
更新#2
您可以做这样的事情:
public abstract class ThreadContextRunnable implements Runnable { private final Map context = ThreadContext.getContext(); @Override public final void run() { if (context != null) { ThreadContext.putAll(context); } try { runWithContext(); } finally { ThreadContext.clearAll(); } } protected abstract void runWithContext(); }
然后您只需要实现runwithContext方法.
问题描述
From this answer https://stackoverflow.com/a/25125159/4367326 I have routingAppender working but I want to set the ThreadContext for every thread in the program.
When I set
ThreadContext.put("logFileName", "TestLogFile");
it works for the main thread and logs as expected but not for any other threads in my application. How can I achieve this?
推荐答案
Every child thread will inherit fathers ThreadContext state if you set up system property isThreadContextMapInheritable to true. But this will not work for Executors so you need to manually copy data from one thread to another.
Update#2
You can do something like this:
public abstract class ThreadContextRunnable implements Runnable { private final Map context = ThreadContext.getContext(); @Override public final void run() { if (context != null) { ThreadContext.putAll(context); } try { runWithContext(); } finally { ThreadContext.clearAll(); } } protected abstract void runWithContext(); }
And then you only need to implement runWithContext method.