Class CloseableThreadContext

java.lang.Object
org.apache.logging.log4j.CloseableThreadContext

public class CloseableThreadContext extends Object
Adds entries to the stack or map and them removes them when the object is closed, e.g. as part of a try-with-resources. User code can now look like this:
 try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key1, value1).put(key2, value2)) {
     callSomeMethodThatLogsALot();

 // Entries for key1 and key2 are automatically removed from the ThreadContext map when done.
 }
 
Since:
2.6
  • Method Details

    • push

      public static CloseableThreadContext.Instance push(String message)
      Pushes new diagnostic context information on to the Thread Context Stack. The information will be popped off when the instance is closed.
      Parameters:
      message - The new diagnostic context information.
      Returns:
      a new instance that will back out the changes when closed.
    • push

      public static CloseableThreadContext.Instance push(String message, Object... args)
      Pushes new diagnostic context information on to the Thread Context Stack. The information will be popped off when the instance is closed.
      Parameters:
      message - The new diagnostic context information.
      args - Parameters for the message.
      Returns:
      a new instance that will back out the changes when closed.
    • put

      public static CloseableThreadContext.Instance put(String key, String value)
      Populates the Thread Context Map with the supplied key/value pair. Any existing key in the ThreadContext will be replaced with the supplied value, and restored back to their original value when the instance is closed.
      Parameters:
      key - The key to be added
      value - The value to be added
      Returns:
      a new instance that will back out the changes when closed.
    • pushAll

      public static CloseableThreadContext.Instance pushAll(List<String> messages)
      Populates the Thread Context Stack with the supplied stack. The information will be popped off when the instance is closed.
      Parameters:
      messages - The list of messages to be added
      Returns:
      a new instance that will back out the changes when closed.
      Since:
      2.8
    • putAll

      public static CloseableThreadContext.Instance putAll(Map<String,String> values)
      Populates the Thread Context Map with the supplied key/value pairs. Any existing keys in the ThreadContext will be replaced with the supplied values, and restored back to their original value when the instance is closed.
      Parameters:
      values - The map of key/value pairs to be added
      Returns:
      a new instance that will back out the changes when closed.
      Since:
      2.8