【问题标题】:Log4j's ThreadContext clears the automaticallyLog4j 的 ThreadContext 会自动清除
【发布时间】:2022-08-05 13:53:10
【问题描述】:

我在应用程序开始时将密钥插入ThreadContext 映射,如下所示,

protected void doFilterWrapped(ContentCachingRequestWrapper request,
      ContentCachingResponseWrapper response, FilterChain filterChain)
      throws ServletException, IOException {
    // some code...
    ThreadContext.put(Constants.REQUEST_ID, requestID);
    ThreadContext.put(requestID + Constants.HASH + \"retryCount\", \"-1\");
    // some more code...
  }

现在在其他类中,我正在尝试像这样更新键 requestID + Constants.HASH + \"retryCount\" 的值,

String key = ThreadContext.get(Constants.REQUEST_ID) + Constants.HASH + \"retryCount\";
      if (ThreadContext.containsKey(key)) {
        ThreadContext.put(key, String.valueOf(Integer.valueOf(ThreadContext.get(key)) + 1));
      } else {
        ThreadContext.put(key, \"-1\");
      }
      System.out.println(\"\\n\\n  \" + ThreadContext.get(key) + \" \\n\\n\");

但它只能工作一次,之后它无法找到key,即ThreadContext.containsKey(key)false

有人可以解释一下问题是什么。

  • 有可能其他名为 ThreadContext.init() 的东西会清除持有您价值的上下文映射。尝试在那里设置断点,你会看到
  • 查了一下,没有打过这样的电话。上述两个调用的线程不同,可能是导致问题吗?
  • 线程应该无关紧要,因为 contextMap 是静态字段。当 contains() 返回 false 时,只检查上下文映射中的内容会更容易。另外我不知道这里是否有问题,但这部分\"ThreadContext.get(Constants.REQUEST_ID) + Constants.HASH + \"retryCount\";\" 不应该在这个地方有括号:\"ThreadContext.get(Constants.REQUEST_ID + Constants.HASH + \"retryCount\");\"
  • 我也检查过这个,新的线程是 spring 提供的 rabbitMQ 线程。除了 key = requestId,所有值都消失了。我不知道为什么它的行为如此异常。
  • ThreadContext 仅对当前线程有效。你能解释一下如何在线程之间传递它吗?

标签: java multithreading spring-boot log4j


【解决方案1】:

您是否尝试过设置 thead 上下文可继承的系统属性?在您的应用启动中,添加以下行:

System.setProperty("isThreadContextMapInheritable", "true");

启用此属性后,子线程将继承线程上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多