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

The following examples show how to use org.apache.logging.log4j.ThreadContext#clearAll() . 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: Log4J2Controller.java    From tutorials with MIT License 6 votes vote down vote up
@RequestMapping(value = "/ndc/log4j2", method = RequestMethod.POST)
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
    // Add transactionId and owner to NDC
    ThreadContext.push("tx.id=" + investment.getTransactionId());
    ThreadContext.push("tx.owner=" + investment.getOwner());

    try {
        log4j2BusinessService.transfer(investment.getAmount());
    } finally {
        // take out owner from the NDC stack
        ThreadContext.pop();

        // take out transactionId from the NDC stack
        ThreadContext.pop();

        ThreadContext.clearAll();
    }
    return new ResponseEntity<Investment>(investment, HttpStatus.OK);
}
 
Example 2
Source File: CloudBusImpl3.java    From zstack with Apache License 2.0 6 votes vote down vote up
private void setThreadLoggingContext(Message msg) {
    ThreadContext.clearAll();

    if (msg instanceof APIMessage) {
        ThreadContext.put(Constants.THREAD_CONTEXT_API, msg.getId());
        ThreadContext.put(Constants.THREAD_CONTEXT_TASK_NAME, msg.getClass().getName());
    } else {
        Map<String, String> ctx = msg.getHeaderEntry(THREAD_CONTEXT);
        if (ctx != null) {
            ThreadContext.putAll(ctx);
        }
    }

    if (msg.getHeaders().containsKey(THREAD_CONTEXT_STACK)) {
        List<String> taskStack = msg.getHeaderEntry(THREAD_CONTEXT_STACK);
        ThreadContext.setStack(taskStack);
    }

    if (msg.getHeaders().containsKey(TASK_CONTEXT)) {
        TaskContext.setTaskContext(msg.getHeaderEntry(TASK_CONTEXT));
    }
}
 
Example 3
Source File: MdcActivationListenerTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
    org.apache.log4j.MDC.put("test", true);
    log4jMdcWorking = (Boolean) org.apache.log4j.MDC.get("test");
    MDC.clear();
    org.apache.log4j.MDC.clear();
    ThreadContext.clearAll();
    loggingConfiguration = config.getConfig(LoggingConfiguration.class);
    // initializes thread eagerly to avoid InheritableThreadLocal to inherit values to this thread
    executorService.submit(() -> {}).get();
}
 
Example 4
Source File: SocketAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() throws Exception {
    tcpServer = new TcpSocketTestServer(PORT);
    tcpServer.start();
    udpServer = new UdpSocketTestServer();
    udpServer.start();
    LoggerContext.getContext().reconfigure();
    ThreadContext.clearAll();
}
 
Example 5
Source File: SocketAppenderBufferSizeTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@After
public void teardown() {
    tcpServer.shutdown();
    loggerContext = null;
    logger = null;
    tcpServer.reset();
    ThreadContext.clearAll();
}
 
Example 6
Source File: SocketAppenderBufferSizeTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    tcpServer = new TcpSocketTestServer(AvailablePortFinder.getNextAvailable());
    tcpServer.start();
    ThreadContext.clearAll();
    loggerContext = loggerContextRule.getLoggerContext();
    logger = loggerContext.getLogger(SocketAppenderBufferSizeTest.class.getName());
}
 
Example 7
Source File: GelfAppenderTest.java    From log4j2-gelf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThreadContext() {
    ThreadContext.push("Message only");
    ThreadContext.push("int", 1);
    ThreadContext.push("int-long-string", 1, 2L, "3");
    ThreadContext.put("key", "value");

    logger.info("Hello World");

    ThreadContext.clearAll();
}
 
Example 8
Source File: YamlLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() {
    ThreadContext.clearAll();
    ConfigurationFactory.setConfigurationFactory(cf);
    final LoggerContext ctx = LoggerContext.getContext();
    ctx.reconfigure();
}
 
Example 9
Source File: StepImpl.java    From jesterj with Apache License 2.0 5 votes vote down vote up
private void reportDocStatus(Status status, Document document, String message, Object... messageParams) {
  try {
    ThreadContext.put(JesterJAppender.JJ_INGEST_DOCID, document.getId());
    ThreadContext.put(JesterJAppender.JJ_INGEST_SOURCE_SCANNER, document.getSourceScannerName());
    document.setStatus(status);
    log.info(status.getMarker(), message, messageParams);
  } catch (AppenderLoggingException e) {
    if (Main.isNotShuttingDown()) {
      log.error("Could not contact our internal Cassandra!!!" + e);
    }
  } finally {
    ThreadContext.clearAll();
  }
}
 
Example 10
Source File: ProgressReportService.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void setThreadContext(ProgressReportCmd cmd) {
    ThreadContext.clearAll();
    if (cmd.getThreadContextMap() != null) {
        ThreadContext.putAll(cmd.getThreadContextMap());
    }
    if (cmd.getThreadContextStack() != null) {
        ThreadContext.setStack(cmd.getThreadContextStack());
    }
}
 
Example 11
Source File: ThreadContextUtils.java    From zstack with Apache License 2.0 5 votes vote down vote up
public static Runnable saveThreadContext() {
    ThreadContextMapSaved savedThread = new ThreadContextMapSaved();
    savedThread.contextMap = ThreadContext.getContext();
    savedThread.contextStack = ThreadContext.cloneStack();

    return () -> {
        ThreadContext.clearAll();
        ThreadContext.putAll(savedThread.contextMap);
        ThreadContext.setStack(savedThread.contextStack.asList());
    };
}
 
Example 12
Source File: JwtAuthenticationTokenFilter.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response ,
								  FilterChain chain ) throws ServletException, IOException {
	final String authToken = this.extractAuthTokenFromRequest( request , this.tokenHeader );
	String username = null;
	if ( StringUtils.isNotBlank( authToken ) ) {
		username  = jwtTokenUtil.getUsernameFromToken( authToken );
	}

	LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username );

	if ( username != null && SecurityContextHolder.getContext().getAuthentication() == null ) {
		// 对于简单的验证,只需检查令牌的完整性即可。 您不必强制调用数据库。 由你自己决定
		// 是否查询数据看情况,目前是查询数据库
		UserDetails userDetails = this.userDetailsService.loadUserByUsername( username );
		if ( jwtTokenUtil.validateToken( authToken , userDetails ) ) {
			UsernamePasswordAuthenticationToken authentication =
				new UsernamePasswordAuthenticationToken( userDetails , null , userDetails.getAuthorities() );

			ThreadContext.put( USER_ID , String.valueOf( ( ( BasicJwtUser ) userDetails ).getId() ) );
			ThreadContext.put( USER_NAME , username );

			authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails( request ) );

			LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username );

			LogUtils.getLogger().debug( "该 " + username + "用户已认证, 设置安全上下文" );

			SecurityContextHolder.getContext().setAuthentication( authentication );
		}
	}
	chain.doFilter( request , response );
	ThreadContext.clearAll();
}
 
Example 13
Source File: Log4JSegmentListenerTest.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setupAWSXRay() {
    Emitter blankEmitter = Mockito.mock(Emitter.class);
    Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.any());
    Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.any());
    Log4JSegmentListener segmentListener = new Log4JSegmentListener();

    AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
                                                    .withEmitter(blankEmitter)
                                                    .withSegmentListener(segmentListener)
                                                    .build());
    AWSXRay.clearTraceEntity();
    ThreadContext.clearAll();
}
 
Example 14
Source File: JsonLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() {
    ThreadContext.clearAll();
    ConfigurationFactory.setConfigurationFactory(cf);
    final LoggerContext ctx = LoggerContext.getContext();
    ctx.reconfigure();
}
 
Example 15
Source File: SocketAppenderTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@After
public void teardown() {
    ThreadContext.clearAll();
    removeAndStopAppenders();
    reset();
}
 
Example 16
Source File: SystemdJournalAppenderIntegrationTest.java    From log4j-systemd-journal-appender with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Before
public void clearMdc() {
    ThreadContext.clearAll();
}
 
Example 17
Source File: FDBDatabaseRunnerTest.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
@Test
void testRestoreMdc() {
    Executor oldExecutor = FDBDatabaseFactory.instance().getExecutor();
    try {
        ThreadContext.clearAll();
        ThreadContext.put("outer", "Echidna");
        final Map<String, String> outer = ThreadContext.getContext();
        final ImmutableMap<String, String> restored = ImmutableMap.of("restored", "Platypus");

        FDBDatabaseFactory.instance().setExecutor(new ContextRestoringExecutor(
                new ForkJoinPool(2), ImmutableMap.of("executor", "Water Bear")));
        AtomicInteger attempts = new AtomicInteger(0);
        final FDBDatabaseRunner runner = new FDBDatabaseRunnerImpl(database, null, restored);
        List<Map<String, String>> threadContexts = new Vector<>();
        Consumer<String> saveThreadContext =
                name -> threadContexts.add(threadContextPlus(name, attempts.get(), ThreadContext.getContext()));
        final String runnerRunAsyncName = "runner runAsync";
        final String supplyAsyncName = "supplyAsync";
        final String handleName = "handle";

        // Delay starting the future until all callbacks have been set up so that the handle lambda
        // runs in the context-restoring executor.
        CompletableFuture<Void> signal = new CompletableFuture<>();
        CompletableFuture<?> task = runner.runAsync(recordContext -> {
            saveThreadContext.accept(runnerRunAsyncName);
            return signal.thenCompose(vignore -> CompletableFuture.supplyAsync(() -> {
                saveThreadContext.accept(supplyAsyncName);
                if (attempts.getAndIncrement() == 0) {
                    throw new RecordCoreRetriableTransactionException("Retriable and lessener",
                            new FDBException("not_committed", 1020));
                } else {
                    return null;
                }
            }, recordContext.getExecutor()));
        }).handle((result, exception) -> {
            saveThreadContext.accept(handleName);
            return exception;

        });
        signal.complete(null);
        assertNull(task.join());
        List<Map<String, String>> expected = ImmutableList.of(
                // first attempt:
                // it is known behavior that the first will be run in the current context
                threadContextPlus(runnerRunAsyncName, 0, outer),
                threadContextPlus(supplyAsyncName, 0, restored),
                // second attempt
                // the code that creates the future, should now have the correct MDC
                threadContextPlus(runnerRunAsyncName, 1, restored),
                threadContextPlus(supplyAsyncName, 1, restored),
                // handle
                // this should also have the correct MDC
                threadContextPlus(handleName, 2, restored));
        assertEquals(expected, threadContexts);
        assertEquals(outer, ThreadContext.getContext());
    } finally {
        FDBDatabaseFactory.instance().setExecutor(oldExecutor);
    }

}
 
Example 18
Source File: JsonLayoutTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void cleanupClass() {
    ConfigurationFactory.removeConfigurationFactory(cf);
    ThreadContext.clearAll();
}
 
Example 19
Source File: YamlLayoutTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void cleanupClass() {
    ConfigurationFactory.removeConfigurationFactory(cf);
    ThreadContext.clearAll();
}
 
Example 20
Source File: Log4J2Runnable.java    From tutorials with MIT License 3 votes vote down vote up
public void run() {

        ThreadContext.put("transaction.id", tx.getTransactionId());
        ThreadContext.put("transaction.owner", tx.getSender());

        log4j2BusinessService.transfer(tx.getAmount());

        ThreadContext.clearAll();

    }