Java Code Examples for org.apache.logging.log4j.ThreadContext#remove()

The following examples show how to use org.apache.logging.log4j.ThreadContext#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Log4JSegmentListener.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Maps the AWS-XRAY-TRACE-ID key to the formatted ID of the entity that's just been created in the Log4J ThreadContext.
 * Does not perform injection if entity is not available or not sampled, since then the given entity would not be displayed
 * in X-Ray console.
 *
 * @param oldEntity the previous entity or null
 * @param newEntity the new entity, either a subsegment or segment
 */
@Override
public void onSetEntity(Entity oldEntity, Entity newEntity) {
    if (newEntity == null) {
        ThreadContext.remove(TRACE_ID_KEY);
        return;
    }

    Segment segment =  newEntity instanceof Segment ? ((Segment) newEntity) : newEntity.getParentSegment();

    if (segment != null && segment.getTraceId() != null && segment.isSampled() && newEntity.getId() != null) {
        String fullPrefix = StringValidator.isNullOrBlank(this.prefix) ? "" : this.prefix + ": ";
        ThreadContext.put(TRACE_ID_KEY, fullPrefix + segment.getTraceId() + "@" + newEntity.getId());
    } else {
        ThreadContext.remove(TRACE_ID_KEY);  // Ensure traces don't spill over to unlinked messages
    }
}
 
Example 2
Source File: BatchProcessor.java    From jesterj with Apache License 2.0 6 votes vote down vote up
private void sendBatch(ConcurrentBiMap<Document, T> oldBatch) {
  // there's a small window where the same BiMap could be grabbed by a timer and a full batch causing a double
  // send. Thus we have a lock to ensure that the oldBatch.clear() in the finally is called
  // before the second thread tries to send the same batch. We tolerate this because it means batches can fill up
  // while sending is in progress.
  synchronized (sendLock) {
    if (oldBatch.size() == 0) {
      return;
    }
    try {
      batchOperation(oldBatch);
    } catch (Exception e) {
      // we may have a single bad document...
      //noinspection ConstantConditions
      if (exceptionIndicatesDocumentIssue(e)) {
        individualFallbackOperation(oldBatch, e);
      } else {
        perDocumentFailure(oldBatch, e);
      }
    } finally {
      ThreadContext.remove(JesterJAppender.JJ_INGEST_DOCID);
      ThreadContext.remove(JesterJAppender.JJ_INGEST_SOURCE_SCANNER);
      oldBatch.clear();
    }
  }
}
 
Example 3
Source File: ContextMapLookupTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            final File logFile = new File("target",
                description.getClassName() + '.' + description.getMethodName() + ".log");
            ThreadContext.put("testClassName", description.getClassName());
            ThreadContext.put("testMethodName", description.getMethodName());
            try {
                base.evaluate();
            } finally {
                ThreadContext.remove("testClassName");
                ThreadContext.remove("testMethodName");
                if (logFile.exists()) {
                    logFile.deleteOnExit();
                }
            }
        }
    };
}
 
Example 4
Source File: ThreadContextMapFilterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilter() {
    ThreadContext.put("userid", "testuser");
    ThreadContext.put("organization", "Apache");
    final KeyValuePair[] pairs = new KeyValuePair[] { new KeyValuePair("userid", "JohnDoe"),
                                                new KeyValuePair("organization", "Apache")};
    ThreadContextMapFilter filter = ThreadContextMapFilter.createFilter(pairs, "and", null, null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.remove("userid");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.put("userid", "JohnDoe");
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null));
    ThreadContext.put("organization", "ASF");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.clearMap();
    filter = ThreadContextMapFilter.createFilter(pairs, "or", null, null);
    filter.start();
    assertTrue(filter.isStarted());
    ThreadContext.put("userid", "testuser");
    ThreadContext.put("organization", "Apache");
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.put("organization", "ASF");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.remove("organization");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    final KeyValuePair[] single = new KeyValuePair[] {new KeyValuePair("userid", "testuser")};
    filter = ThreadContextMapFilter.createFilter(single, null, null, null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    ThreadContext.clearMap();
}
 
Example 5
Source File: OpenCensusTraceContextDataInjectorTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void rawContextDataWithTracingData() {
  OpenCensusTraceContextDataInjector plugin = new OpenCensusTraceContextDataInjector();
  SpanContext spanContext =
      SpanContext.create(
          TraceId.fromLowerBase16("e17944156660f55b8cae5ce3f45d4a40"),
          SpanId.fromLowerBase16("fc3d2ba0d283b66a"),
          TraceOptions.builder().setIsSampled(true).build(),
          EMPTY_TRACESTATE);
  Scope scope = tracer.withSpan(new TestSpan(spanContext));
  try {
    String key = "myTestKey";
    ThreadContext.put(key, "myTestValue");
    try {
      assertThat(plugin.rawContextData().toMap())
          .containsExactly(
              "myTestKey",
              "myTestValue",
              "traceId",
              "e17944156660f55b8cae5ce3f45d4a40",
              "spanId",
              "fc3d2ba0d283b66a",
              "traceSampled",
              "true");
    } finally {
      ThreadContext.remove(key);
    }
  } finally {
    scope.close();
  }
}
 
Example 6
Source File: LogEventFactoryInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void before(Object target) {
    Trace trace = traceContext.currentTraceObject();

    if (trace == null) {
        ThreadContext.remove(TRANSACTION_ID);
        ThreadContext.remove(SPAN_ID);
        return;
    } else {
        ThreadContext.put(TRANSACTION_ID, trace.getTraceId().getTransactionId());
        ThreadContext.put(SPAN_ID, String.valueOf(trace.getTraceId().getSpanId()));
    }
}
 
Example 7
Source File: ThreadContextScopeDecorator.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public boolean update(String name, @Nullable String value) {
  if (value != null) {
    ThreadContext.put(name, value);
  } else if (ThreadContext.containsKey(name)) {
    ThreadContext.remove(name);
  } else {
    return false;
  }
  return true;
}
 
Example 8
Source File: ThreadContextDataInjectorTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void prepareThreadContext(boolean isThreadContextMapInheritable) {
    System.setProperty("log4j2.isThreadContextMapInheritable", Boolean.toString(isThreadContextMapInheritable));
    PropertiesUtil.getProperties().reload();
    ThreadContextTest.reinitThreadContext();
    ThreadContext.remove("baz");
    ThreadContext.put("foo", "bar");
}
 
Example 9
Source File: ThreadContextDataInjectorTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@After
public void after() {
    ThreadContext.remove("foo");
    ThreadContext.remove("baz");
    System.clearProperty("log4j2.threadContextMap");
    System.clearProperty("log4j2.isThreadContextMapInheritable");
}
 
Example 10
Source File: SocketAppenderTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
static void testTcpAppender(final TcpSocketTestServer tcpTestServer, final Logger logger, final int bufferSize)
        throws Exception {
    // @formatter:off
    final SocketAppender appender = SocketAppender.newBuilder()
            .setHost("localhost")
            .setPort(tcpTestServer.getLocalPort())
            .setReconnectDelayMillis(-1)
            .setName("test")
            .setImmediateFail(false)
            .setBufferSize(bufferSize)
            .setLayout(JsonLayout.newBuilder().setProperties(true).build())
            .build();
    // @formatter:on
    appender.start();
    Assert.assertEquals(bufferSize, appender.getManager().getByteBuffer().capacity());

    // set appender on root and set level to debug
    logger.addAppender(appender);
    logger.setAdditive(false);
    logger.setLevel(Level.DEBUG);
    final String tcKey = "UUID";
    final String expectedUuidStr = UUID.randomUUID().toString();
    ThreadContext.put(tcKey, expectedUuidStr);
    ThreadContext.push(expectedUuidStr);
    final String expectedExMsg = "This is a test";
    try {
        logger.debug("This is a test message");
        final Throwable child = new LoggingException(expectedExMsg);
        logger.error("Throwing an exception", child);
        logger.debug("This is another test message");
    } finally {
        ThreadContext.remove(tcKey);
        ThreadContext.pop();
    }
    Thread.sleep(250);
    LogEvent event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS);
    assertNotNull("No event retrieved", event);
    assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("This is a test message"));
    assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 0);
    assertEquals(expectedUuidStr, event.getContextData().getValue(tcKey));
    event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS);
    assertNotNull("No event retrieved", event);
    assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("Throwing an exception"));
    assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 1);
    assertEquals(expectedUuidStr, event.getContextStack().pop());
    assertNotNull(event.getThrownProxy());
    assertEquals(expectedExMsg, event.getThrownProxy().getMessage());
}
 
Example 11
Source File: AbstractAsyncThreadContextTestBase.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testAsyncLogWritesToLog() throws Exception {
    final File[] files = new File[] {
            new File("target", "AsyncLoggerTest.log"), //
            new File("target", "SynchronousContextTest.log"), //
            new File("target", "AsyncLoggerAndAsyncAppenderTest.log"), //
            new File("target", "AsyncAppenderContextTest.log"), //
    };
    for (final File f : files) {
        f.delete();
    }

    ThreadContext.push("stackvalue");
    ThreadContext.put("KEY", "mapvalue");

    final Logger log = LogManager.getLogger("com.foo.Bar");
    final LoggerContext loggerContext = LogManager.getContext(false);
    final String loggerContextName = loggerContext.getClass().getSimpleName();
    RingBufferAdmin ring;
    if (loggerContext instanceof AsyncLoggerContext) {
        ring = ((AsyncLoggerContext) loggerContext).createRingBufferAdmin();
    } else {
        ring = ((AsyncLoggerConfig) ((org.apache.logging.log4j.core.Logger) log).get()).createRingBufferAdmin("");
    }

    for (int i = 0; i < LINE_COUNT; i++) {
        while (i >= 128 && ring.getRemainingCapacity() == 0) { // buffer may be full
            Thread.sleep(1);
        }
        if ((i & 1) == 1) {
            ThreadContext.put("count", String.valueOf(i));
        } else {
            ThreadContext.remove("count");
        }
        log.info("{} {} {} i={}", contextImpl, contextMap(), loggerContextName, Unbox.box(i));
    }
    ThreadContext.pop();
    CoreLoggerContexts.stopLoggerContext(false, files[0]); // stop async thread

    checkResult(files[0], loggerContextName);
    if (asyncMode == Mode.MIXED || asyncMode == Mode.BOTH_ALL_ASYNC_AND_MIXED) {
        for (int i = 1; i < files.length; i++) {
            checkResult(files[i], loggerContextName);
        }
    }
    LogManager.shutdown();
}
 
Example 12
Source File: Log4jMDCAdapter.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void remove(final String key) {
    ThreadContext.remove(key);
}
 
Example 13
Source File: MDC.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public static void remove(final String key) {
    localMap.get().remove(key);
    ThreadContext.remove(key);
}
 
Example 14
Source File: MDC.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public static void remove(final String key) {
    localMap.get().remove(key);
    ThreadContext.remove(key);
}
 
Example 15
Source File: Log4jMDCAdapter.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void remove(final String key) {
    ThreadContext.remove(key);
}
 
Example 16
Source File: ContextLog4j2Util.java    From chronus with Apache License 2.0 4 votes vote down vote up
/**
 * 从ThreadContext清理对象
 */
public static void removeContextFromThreadContext() {
    ThreadContext.remove(ContextConstKey.REQUEST_NO);
    ThreadContext.remove(ContextConstKey.CONSUMER_IP);
}
 
Example 17
Source File: ThreadContextBenchmark.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Benchmark
public void putAndRemove() {
    ThreadContext.put("someKey", "someValue");
    ThreadContext.remove("someKey");
}
 
Example 18
Source File: Log4j2MsgIdHolder.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
protected void clear0() {
    ThreadContext.remove(MSG_ID_KEY);
}
 
Example 19
Source File: Log4JSegmentListener.java    From aws-xray-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * Removes the AWS-XRAY-TRACE-ID key from the ThreadContext upon the completion of each segment.
 *
 * @param entity
 * The segment that has just ended
 */
@Override
public void onClearEntity(Entity entity) {
    ThreadContext.remove(TRACE_ID_KEY);
}