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

The following examples show how to use org.apache.logging.log4j.ThreadContext#push() . 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: AsyncLoggerThreadContextTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncLogWritesToLog() throws Exception {
    final File file = new File("target", "AsyncLoggerTest.log");
    // System.out.println(f.getAbsolutePath());
    file.delete();
    
    ThreadContext.push("stackvalue");
    ThreadContext.put("KEY", "mapvalue");
    
    final Logger log = LogManager.getLogger("com.foo.Bar");
    final String msg = "Async logger msg";
    log.info(msg, new InternalError("this is not a real error"));
    CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

    final BufferedReader reader = new BufferedReader(new FileReader(file));
    final String line1 = reader.readLine();
    reader.close();
    file.delete();
    assertNotNull("line1", line1);
    assertTrue("line1 correct", line1.contains(msg));

    assertTrue("ThreadContext.map", line1.contains("mapvalue"));
    assertTrue("ThreadContext.stack", line1.contains("stackvalue"));
}
 
Example 2
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 3
Source File: ProgressReportService.java    From zstack with Apache License 2.0 5 votes vote down vote up
public static void createSubTaskProgress(String fmt, Object...args) {
    if (!ProgressGlobalConfig.PROGRESS_ON.value(Boolean.class)) {
        return;
    }

    if (!ThreadContext.containsKey(Constants.THREAD_CONTEXT_API)) {
        if (args != null) {
            logger.warn(String.format("no task uuid found for:" + fmt, args));
        } else {
            logger.warn(String.format("no task uuid found for:" + fmt, args));
        }
        return;
    }

    ThreadContext.put(Constants.THREAD_CONTEXT_PROGRESS_ENABLED, "true");

    String parentUuid = getParentUuid();
    String taskUuid = Platform.getUuid();
    ThreadContext.push(taskUuid);
    ThreadContext.push(Platform.getUuid());

    TaskProgressVO vo = new TaskProgressVO();
    vo.setApiId(ThreadContext.get(Constants.THREAD_CONTEXT_API));
    vo.setTaskUuid(taskUuid);
    vo.setParentUuid(parentUuid);
    vo.setContent(fmt);
    if (args != null) {
        vo.setArguments(JSONObjectUtil.toJsonString(args));
    }
    vo.setType(TaskType.Task);
    vo.setTime(System.currentTimeMillis());
    vo.setManagementUuid(Platform.getManagementServerId());
    vo.setTaskName(ThreadContext.get(Constants.THREAD_CONTEXT_TASK_NAME));

    Platform.getComponentLoader().getComponent(DatabaseFacade.class).persist(vo);

    // use content as the subtask name
    ThreadContext.put(Constants.THREAD_CONTEXT_TASK_NAME, vo.getContent());
}
 
Example 4
Source File: NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test3() {
    ThreadContext.push("foo");
    ThreadContext.push("bar");
    ThreadContext.push("baz");
    testConverter("[foo, bar, baz]");
}
 
Example 5
Source File: Log4j1NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test3() {
    ThreadContext.push("foo");
    ThreadContext.push("bar");
    ThreadContext.push("baz");
    testConverter("foo bar baz");
}
 
Example 6
Source File: Log4j1NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test3() {
    ThreadContext.push("foo");
    ThreadContext.push("bar");
    ThreadContext.push("baz");
    testConverter("foo bar baz");
}
 
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: Log4j1NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test2() {
    ThreadContext.push("foo");
    ThreadContext.push("bar");
    testConverter("foo bar");
}
 
Example 9
Source File: Log4j1NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test1() {
    ThreadContext.push("foo");
    testConverter("foo");
}
 
Example 10
Source File: Log4j1NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test1() {
    ThreadContext.push("foo");
    testConverter("foo");
}
 
Example 11
Source File: Log4j1NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test2() {
    ThreadContext.push("foo");
    ThreadContext.push("bar");
    testConverter("foo bar");
}
 
Example 12
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 13
Source File: NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test1() {
    ThreadContext.push("foo");
    testConverter("[foo]");
}
 
Example 14
Source File: NdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test2() {
    ThreadContext.push("foo");
    ThreadContext.push("bar");
    testConverter("[foo, bar]");
}
 
Example 15
Source File: NoSqlDatabaseManagerTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testWriteInternal02() {
    given(connection.isClosed()).willReturn(false);
    given(message.getFormattedMessage()).willReturn("Another cool message 02.");

    try (final NoSqlDatabaseManager<?> manager = NoSqlDatabaseManager.getNoSqlDatabaseManager("name", 0,
        provider)) {
        manager.startup();

        manager.connectAndStart();
        then(provider).should().getConnection();

        final RuntimeException exception = new RuntimeException("This is something cool!");
        final Map<String, String> context = new HashMap<>();
        context.put("hello", "world");
        context.put("user", "pass");

        ThreadContext.push("message1");
        ThreadContext.push("stack2");
        final ThreadContext.ContextStack stack = ThreadContext.getImmutableStack();
        ThreadContext.clearStack();

        final LogEvent event = Log4jLogEvent.newBuilder()
            .setLevel(Level.DEBUG)
            .setLoggerName("com.foo.NoSQLDbTest.testWriteInternal02")
            .setMessage(message)
            .setSource(new StackTraceElement("com.bar.Foo", "anotherMethod03", "Foo.java", 9))
            .setMarker(MarkerManager.getMarker("LoneMarker"))
            .setThreadId(1L)
            .setThreadName("AnotherThread-B")
            .setThreadPriority(1)
            .setTimeMillis(987654321564L)
            .setThrown(exception)
            .setContextData(ContextDataFactory.createContextData(context))
            .setContextStack(stack)
            .build();

        manager.writeInternal(event, null);
        then(connection).should().insertObject(captor.capture());

        final NoSqlObject<Map<String, Object>> inserted = captor.getValue();
        assertNotNull("The inserted value should not be null.", inserted);
        final Map<String, Object> object = inserted.unwrap();
        assertNotNull("The unwrapped object should not be null.", object);

        assertEquals("The level is not correct.", Level.DEBUG, object.get("level"));
        assertEquals("The logger is not correct.", "com.foo.NoSQLDbTest.testWriteInternal02",
            object.get("loggerName"));
        assertEquals("The message is not correct.", "Another cool message 02.", object.get("message"));
        assertEquals("The thread is not correct.", "AnotherThread-B", object.get("threadName"));
        assertEquals("The millis is not correct.", 987654321564L, object.get("millis"));
        assertEquals("The date is not correct.", 987654321564L, ((Date) object.get("date")).getTime());

        assertTrue("The source should be a map.", object.get("source") instanceof Map);
        @SuppressWarnings("unchecked")
        final Map<String, Object> source = (Map<String, Object>) object.get("source");
        assertEquals("The class is not correct.", "com.bar.Foo", source.get("className"));
        assertEquals("The method is not correct.", "anotherMethod03", source.get("methodName"));
        assertEquals("The file name is not correct.", "Foo.java", source.get("fileName"));
        assertEquals("The line number is not correct.", 9, source.get("lineNumber"));

        assertTrue("The marker should be a map.", object.get("marker") instanceof Map);
        @SuppressWarnings("unchecked")
        final Map<String, Object> marker = (Map<String, Object>) object.get("marker");
        assertEquals("The marker name is not correct.", "LoneMarker", marker.get("name"));
        assertNull("The marker parent should be null.", marker.get("parent"));

        assertTrue("The thrown should be a map.", object.get("thrown") instanceof Map);
        @SuppressWarnings("unchecked")
        final Map<String, Object> thrown = (Map<String, Object>) object.get("thrown");
        assertEquals("The thrown type is not correct.", "java.lang.RuntimeException", thrown.get("type"));
        assertEquals("The thrown message is not correct.", "This is something cool!", thrown.get("message"));
        assertTrue("The thrown stack trace should be a list.", thrown.get("stackTrace") instanceof List);
        @SuppressWarnings("unchecked")
        final List<Map<String, Object>> stackTrace = (List<Map<String, Object>>) thrown.get("stackTrace");
        assertEquals("The thrown stack trace length is not correct.", exception.getStackTrace().length,
            stackTrace.size());
        for (int i = 0; i < exception.getStackTrace().length; i++) {
            final StackTraceElement e1 = exception.getStackTrace()[i];
            final Map<String, Object> e2 = stackTrace.get(i);

            assertEquals("Element class name [" + i + "] is not correct.", e1.getClassName(), e2.get("className"));
            assertEquals("Element method name [" + i + "] is not correct.", e1.getMethodName(),
                e2.get("methodName"));
            assertEquals("Element file name [" + i + "] is not correct.", e1.getFileName(), e2.get("fileName"));
            assertEquals("Element line number [" + i + "] is not correct.", e1.getLineNumber(),
                e2.get("lineNumber"));
        }
        assertNull("The thrown should have no cause.", thrown.get("cause"));

        assertTrue("The context map should be a map.", object.get("contextMap") instanceof Map);
        assertEquals("The context map is not correct.", context, object.get("contextMap"));

        assertTrue("The context stack should be list.", object.get("contextStack") instanceof List);
        assertEquals("The context stack is not correct.", stack.asList(), object.get("contextStack"));
    }
}
 
Example 16
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 17
Source File: AbstractLog4j2EcsLayoutTest.java    From ecs-logging-java with Apache License 2.0 4 votes vote down vote up
@Override
public boolean putNdc(String message) {
    ThreadContext.push(message);
    return true;
}