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

The following examples show how to use org.apache.logging.log4j.ThreadContext#put() . 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: MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConverterFullSingle() {
    ThreadContext.clearMap();
    ThreadContext.put("foo", "bar");
    final Message msg = new SimpleMessage("Hello");
    final MdcPatternConverter converter = MdcPatternConverter.newInstance(null);
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg) //
            .build();
    final StringBuilder sb = new StringBuilder();
    converter.format(event, sb);
    final String str = sb.toString();
    final String expected = "{foo=bar}";
    assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected));
}
 
Example 2
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 3
Source File: InterpolatorTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLookup() {
    final Map<String, String> map = new HashMap<>();
    map.put(TESTKEY, TESTVAL);
    final StrLookup lookup = new Interpolator(new MapLookup(map));
    ThreadContext.put(TESTKEY, TESTVAL);
    String value = lookup.lookup(TESTKEY);
    assertEquals(TESTVAL, value);
    value = lookup.lookup("ctx:" + TESTKEY);
    assertEquals(TESTVAL, value);
    value = lookup.lookup("sys:" + TESTKEY);
    assertEquals(TESTVAL, value);
    value = lookup.lookup("SYS:" + TESTKEY2);
    assertEquals(TESTVAL, value);
    value = lookup.lookup("BadKey");
    assertNull(value);
    ThreadContext.clearMap();
    value = lookup.lookup("ctx:" + TESTKEY);
    assertEquals(TESTVAL, value);
    value = lookup.lookup("jndi:" + TEST_CONTEXT_RESOURCE_NAME);
    assertEquals(TEST_CONTEXT_NAME, value);
}
 
Example 4
Source File: DynamicThresholdFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilter() {
    ThreadContext.put("userid", "testuser");
    ThreadContext.put("organization", "apache");
    final KeyValuePair[] pairs = new KeyValuePair[] {
            new KeyValuePair("testuser", "DEBUG"),
            new KeyValuePair("JohnDoe", "warn") };
    final DynamicThresholdFilter filter = DynamicThresholdFilter.createFilter("userid", pairs, Level.ERROR, null,
            null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null));
    ThreadContext.clearMap();
    ThreadContext.put("userid", "JohnDoe");
    ThreadContext.put("organization", "apache");
    LogEvent event = Log4jLogEvent.newBuilder().setLevel(Level.DEBUG).setMessage(new SimpleMessage("Test")).build();
    assertSame(Filter.Result.DENY, filter.filter(event));
    event = Log4jLogEvent.newBuilder().setLevel(Level.ERROR).setMessage(new SimpleMessage("Test")).build();
    assertSame(Filter.Result.NEUTRAL, filter.filter(event));
    ThreadContext.clearMap();
}
 
Example 5
Source File: XmlEvents.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvents() {
    ThreadContext.put("loginId", "JohnDoe");
    ThreadContext.put("ipAddress", "192.168.0.120");
    ThreadContext.put("locale", Locale.US.getDisplayName());
    final TransferMessage msg = new TransferMessage();
    msg.put("ToAccount", "123456");
    msg.put("FromAccount", "123457");
    msg.put("Amount", "200.00");
    EventLogger.logEvent(msg);
    msg.setCompletionStatus("Transfer Complete");
    EventLogger.logEvent(msg);
    ThreadContext.clearMap();
    // TODO: do something with the results

}
 
Example 6
Source File: MCRSessionThreadContext.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void sessionEvent(MCRSessionEvent event) {
    switch (event.getType()) {
        case activated:
            ThreadContext.put("ipAddress", event.getSession().getCurrentIP());
            ThreadContext.put("loginId", event.getSession().getUserInformation().getUserID());
            ThreadContext.put("mcrSession", event.getSession().getID());
            ThreadContext.put("language", event.getSession().getCurrentLanguage());
            break;
        case passivated:
            ThreadContext.clearMap();
            break;

        default:
            break;
    }
}
 
Example 7
Source File: AuditLoggerTest.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuditLogger() {
    auditLogger = buildAuditLogger(catalogReader);

    ThreadContext.put("accountNumber", "12345");
    ThreadContext.put("companyId", "12345");
    ThreadContext.put("userId", "JohnDoe");
    ThreadContext.put("ipAddress", "127.0.0.1");
    ThreadContext.put("environment", "dev");
    ThreadContext.put("product", "TestProduct");
    ThreadContext.put("timeZone", "America/Phoenix");
    ThreadContext.put("loginId", "TestUser");
    Map<String, String> properties = new HashMap<>();
    properties.put("toAccount", "123456");
    properties.put("fromAccount", "111111");
    properties.put("amount", "111.55");
    try {
        auditLogger.logEvent("transfer", properties);
    } catch (Exception ex) {
        ex.printStackTrace();
        fail();
    }
    List<String> msgs = app.getMessages();
    assertNotNull("No messages", msgs);
    assertEquals("No messages", 1, msgs.size());
    String msg = msgs.get(0);
    assertTrue("No companyId", msg.contains("companyId=\"12345\""));
    assertTrue("No ipAddress", msg.contains("ipAddress=\"127.0.0.1\""));
    assertTrue("No toAccount", msg.contains("toAccount=\"123456\""));
}
 
Example 8
Source File: CustomLoggingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenLoggerWithConsoleConfig_whenFilterByThreadContext_thanOK() throws Exception {
    Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_THREAD_CONTEXT");
    ThreadContext.put("userId", "1000");
    logger.info("This is a log-visible user login. Maybe from an admin account?");
    ThreadContext.put("userId", "1001");
    logger.info("This is a log-invisible user login.");
}
 
Example 9
Source File: RequestContext.java    From audit-log-plugin with MIT License 5 votes vote down vote up
public static String getRequestId() {
    String uuidStr = ThreadContext.get(REQUEST_ID);
    if (uuidStr == null) {
        ThreadContext.put(REQUEST_ID, UuidUtil.getTimeBasedUuid().toString());
        uuidStr = ThreadContext.get(REQUEST_ID);
    }
    return uuidStr;
}
 
Example 10
Source File: RequestContext.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
public static String getRequestId() {
    String uuidStr = ThreadContext.get(REQUEST_ID);
    UUID uuid;
    if (uuidStr == null) {
        uuid = UuidUtil.getTimeBasedUuid();
        ThreadContext.put(REQUEST_ID, uuid.toString());
    }
    return uuidStr;
}
 
Example 11
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 12
Source File: PatternLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderFooterThreadContext() throws Exception {
    final PatternLayout layout = PatternLayout.newBuilder().setPattern("%d{UNIX} %m")
            .setConfiguration(ctx.getConfiguration()).setHeader("${ctx:header}").setFooter("${ctx:footer}")
            .build();
    ThreadContext.put("header", "Hello world Header");
    ThreadContext.put("footer", "Hello world Footer");
    final byte[] header = layout.getHeader();
    assertNotNull("No header", header);
    assertTrue("expected \"Hello world Header\", actual " + Strings.dquote(new String(header)),
            new String(header).equals(new String("Hello world Header")));
}
 
Example 13
Source File: Log4jMDCAdapter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked") // nothing we can do about this, restricted by SLF4J API
public void setContextMap(@SuppressWarnings("rawtypes") final Map map) {
    ThreadContext.clearMap();
    for (final Map.Entry<String, String> entry : ((Map<String, String>) map).entrySet()) {
        ThreadContext.put(entry.getKey(), entry.getValue());
    }
}
 
Example 14
Source File: ProgressReportService.java    From zstack with Apache License 2.0 4 votes vote down vote up
public static TaskProgressRange markTaskStage(TaskProgressRange parentStage, TaskProgressRange subStage) {
    TaskProgressRange exactStage = parentStage != null ? transformSubStage(parentStage, subStage) : subStage;
    ThreadContext.put(Constants.THREAD_CONTEXT_TASK_STAGE, exactStage.toString());
    return exactStage;
}
 
Example 15
Source File: RequestContext.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public static void setProductVersion(final String productVersion) {
    ThreadContext.put(PRODUCT_VERSION, productVersion);
}
 
Example 16
Source File: Log4jMDCAdapter.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void put(final String key, final String val) {
    ThreadContext.put(key, val);
}
 
Example 17
Source File: RequestContext.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public static void setUserId(final String id) {
    ThreadContext.put(USER_ID,  id);
}
 
Example 18
Source File: ProgressReportService.java    From zstack with Apache License 2.0 4 votes vote down vote up
private static void taskProgress(TaskType type, 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("no task uuid found for:" + fmt);
        }
        return;
    }

    String apiId = ThreadContext.get(THREAD_CONTEXT_API);

    if (apiId == null) {
        logger.warn("apiId not found");
        return;
    }

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

    String taskUuid = getTaskUuid();
    if (taskUuid.isEmpty()) {
        taskUuid = Platform.getUuid();
    }

    TaskProgressVO vo = new TaskProgressVO();
    vo.setApiId(apiId);
    vo.setTaskUuid(taskUuid);
    vo.setParentUuid(getParentUuid());
    if (args != null) {
        vo.setArguments(JSONObjectUtil.toJsonString(args));
    }
    vo.setType(type);
    vo.setTime(System.currentTimeMillis());
    vo.setManagementUuid(Platform.getManagementServerId());
    vo.setTaskName(ThreadContext.get(Constants.THREAD_CONTEXT_TASK_NAME));

    calculateFmtAndPersist(vo, apiId, type, fmt);
}
 
Example 19
Source File: Main.java    From ict with Apache License 2.0 4 votes vote down vote up
private Log4JConfig() {
    disableRootLevelSetting = System.getProperties().containsKey("log4j.configurationFile");
    ThreadContext.put(CTX_KEY_LOG_DIR, Main.DEFAULT_LOG_DIR_PATH);
    ThreadContext.put(CTX_KEY_LOG_FILENAME, Main.DEFAULT_LOG_FILE_NAME);
    ThreadContext.put(CTX_KEY_LOG_FILE_ENABLED, DEFAULT_ENABLE_LOGFILE_CREATION_ON_STARTUP);
}
 
Example 20
Source File: RequestContext.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public static void setProductName(final String productName) {
    ThreadContext.put(PRODUCT_NAME, productName);
}