为应用程序中的所有线程设置 ThreadContext[英] Setting ThreadContext for all threads in application

本文是小编为大家收集整理的关于为应用程序中的所有线程设置 ThreadContext的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

来自此答案 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方法.

本文地址:https://www.itbaoku.cn/post/1575072.html

问题描述

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.