Java Code Examples for org.apache.logging.log4j.ThreadContext

The following examples show how to use org.apache.logging.log4j.ThreadContext. These examples are extracted from open source projects. 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 Project: logging-log4j2   Author: apache   File: StrSubstitutorTest.java    License: 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));
    final StrSubstitutor subst = new StrSubstitutor(lookup);
    ThreadContext.put(TESTKEY, TESTVAL);
    String value = subst.replace("${TestKey}-${ctx:TestKey}-${sys:TestKey}");
    assertEquals("TestValue-TestValue-TestValue", value);
    value = subst.replace("${BadKey}");
    assertEquals("${BadKey}", value);

    value = subst.replace("${BadKey:-Unknown}-${ctx:BadKey:-Unknown}-${sys:BadKey:-Unknown}");
    assertEquals("Unknown-Unknown-Unknown", value);
    value = subst.replace("${BadKey:-Unknown}-${ctx:BadKey}-${sys:BadKey:-Unknown}");
    assertEquals("Unknown-${ctx:BadKey}-Unknown", value);
    value = subst.replace("${BadKey:-Unknown}-${ctx:BadKey:-}-${sys:BadKey:-Unknown}");
    assertEquals("Unknown--Unknown", value);
}
 
Example #2
Source Project: logging-log4j2   Author: apache   File: MdcPatternConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConverterFullEmpty() {
    ThreadContext.clearMap();
    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 = "{}";
    assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected));
}
 
Example #3
Source Project: logging-log4j2   Author: apache   File: GelfLayoutTest3.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void gelfLayout() throws IOException {
    final Logger logger = context.getLogger();
    ThreadContext.put("loginId", "rgoers");
    ThreadContext.put("internalId", "12345");
    logger.info("My Test Message");
    final String gelf = context.getListAppender("list").getMessages().get(0);
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode json = mapper.readTree(gelf);
    assertEquals("My Test Message", json.get("short_message").asText());
    assertEquals("myhost", json.get("host").asText());
    assertNotNull(json.get("_loginId"));
    assertEquals("rgoers", json.get("_loginId").asText());
    assertNull(json.get("_internalId"));
    assertNull(json.get("_requestId"));
    String message = json.get("full_message").asText();
    assertTrue(message.contains("loginId=rgoers"));
    assertTrue(message.contains("GelfLayoutTest3"));
}
 
Example #4
Source Project: sofa-common-tools   Author: sofastack   File: LogbackIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThreadContextConfiguration() {
    try {
        System.setProperty(Constants.LOGBACK_MIDDLEWARE_LOG_DISABLE_PROP_KEY, "true");
        SPACES_MAP.remove(new SpaceId(TEST_SPACE));
        LoggerSpaceManager.getLoggerBySpace(LogbackIntegrationTest.class.getCanonicalName(),
            TEST_SPACE);
        ThreadContext.put("testKey", "testValue");
        ThreadContext.put("logging.path", "anyPath");
        Map<String, Object> properties = new HashMap<String, Object>();
        SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
        springApplication.setDefaultProperties(properties);
        springApplication.run(new String[] {});
        Assert.assertTrue("testValue".equals(ThreadContext.get("testKey")));
        Assert.assertTrue(Constants.LOGGING_PATH_DEFAULT.equals(ThreadContext
            .get("logging.path")));
    } finally {
        System.getProperties().remove(Constants.LOGBACK_MIDDLEWARE_LOG_DISABLE_PROP_KEY);
    }
}
 
Example #5
Source Project: tutorials   Author: eugenp   File: Log4J2Controller.java    License: 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 #6
Source Project: logging-log4j2   Author: apache   File: ThreadContextUtilityClass.java    License: Apache License 2.0 6 votes vote down vote up
public static void perfTest() throws Exception {
    ThreadContext.clearMap();
    final Timer complete = new Timer("ThreadContextTest");
    complete.start();
    ThreadContext.put("Var1", "value 1");
    ThreadContext.put("Var2", "value 2");
    ThreadContext.put("Var3", "value 3");
    ThreadContext.put("Var4", "value 4");
    ThreadContext.put("Var5", "value 5");
    ThreadContext.put("Var6", "value 6");
    ThreadContext.put("Var7", "value 7");
    ThreadContext.put("Var8", "value 8");
    ThreadContext.put("Var9", "value 9");
    ThreadContext.put("Var10", "value 10");
    final int loopCount = 1000000;
    final Timer timer = new Timer("ThreadContextCopy", loopCount);
    timer.start();
    for (int i = 0; i < loopCount; ++i) {
        final Map<String, String> map = ThreadContext.getImmutableContext();
        assertNotNull(map);
    }
    timer.stop();
    complete.stop();
    System.out.println(timer.toString());
    System.out.println(complete.toString());
}
 
Example #7
Source Project: logging-log4j2   Author: apache   File: AsyncLogger.java    License: Apache License 2.0 6 votes vote down vote up
private void initTranslator(final RingBufferLogEventTranslator translator, final String fqcn,
                            final StackTraceElement location, final Level level, final Marker marker,
                            final Message message, final Throwable thrown) {

    translator.setBasicValues(this, name, marker, fqcn, level, message, //
        // don't construct ThrowableProxy until required
        thrown,

        // needs shallow copy to be fast (LOG4J2-154)
        ThreadContext.getImmutableStack(), //

        location,
        CLOCK, //
        nanoClock //
    );
}
 
Example #8
Source Project: zstack   Author: zstackio   File: CephPrimaryStorageBase.java    License: Apache License 2.0 6 votes vote down vote up
private void handle(CephToCephMigrateVolumeSegmentMsg msg) {
    final CephToCephMigrateVolumeSegmentCmd cmd = new CephToCephMigrateVolumeSegmentCmd();
    cmd.setParentUuid(msg.getParentUuid());
    cmd.setResourceUuid(msg.getResourceUuid());
    cmd.setSrcInstallPath(msg.getSrcInstallPath());
    cmd.setDstInstallPath(msg.getDstInstallPath());
    cmd.setDstMonHostname(msg.getDstMonHostname());
    cmd.setDstMonSshUsername(msg.getDstMonSshUsername());
    cmd.setDstMonSshPassword(msg.getDstMonSshPassword());
    cmd.setDstMonSshPort(msg.getDstMonSshPort());

    final String apiId = ThreadContext.get(Constants.THREAD_CONTEXT_API);
    final CephToCephMigrateVolumeSegmentReply reply = new CephToCephMigrateVolumeSegmentReply();
    new HttpCaller<>(CEPH_TO_CEPH_MIGRATE_VOLUME_SEGMENT_PATH, cmd, StorageMigrationRsp.class, new ReturnValueCompletion<StorageMigrationRsp>(msg) {
        @Override
        public void success(StorageMigrationRsp returnValue) {
            bus.reply(msg, reply);
        }

        @Override
        public void fail(ErrorCode errorCode) {
            reply.setError(errorCode);
            bus.reply(msg, reply);
        }
    }, TimeUnit.MILLISECONDS, msg.getTimeout()).specifyOrder(apiId).call();
}
 
Example #9
Source Project: zstack   Author: zstackio   File: RevertVolumeSnapshotLongJob.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start(LongJobVO job, ReturnValueCompletion<APIEvent> completion) {
    RevertVolumeSnapshotMsg msg = new RevertVolumeSnapshotMsg();
    APIRevertVolumeFromSnapshotMsg apiMessage = JSONObjectUtil.toObject(job.getJobData(), APIRevertVolumeFromSnapshotMsg.class);
    msg.setSnapshotUuid(apiMessage.getSnapshotUuid());
    msg.setVolumeUuid(apiMessage.getVolumeUuid());
    msg.setTreeUuid(apiMessage.getTreeUuid());
    msg.setSession(apiMessage.getSession());
    bus.makeServiceIdByManagementNodeId(msg, VolumeSnapshotConstant.SERVICE_ID, getRoutedMnId(apiMessage));
    bus.send(msg, new CloudBusCallBack(completion) {
        @Override
        public void run(MessageReply reply) {
            auditResourceUuid = msg.getVolumeUuid();
            if (reply.isSuccess()) {
                APIRevertVolumeFromSnapshotEvent evt = new APIRevertVolumeFromSnapshotEvent(ThreadContext.get(Constants.THREAD_CONTEXT_API));

                completion.success(evt);
            } else {
                completion.fail(reply.getError());
            }
        }
    });
}
 
Example #10
Source Project: mycore   Author: MyCoRe-Org   File: MCRSessionThreadContext.java    License: 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 #11
Source Project: zstack   Author: zstackio   File: LongJobManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void submitLongJob(SubmitLongJobMsg msg, CloudBusCallBack submitCallBack, Consumer<APIEvent> jobCallBack) {
    String apiId = ThreadContext.get(Constants.THREAD_CONTEXT_API);
    longJobCallBacks.put(apiId, jobCallBack);
    bus.makeLocalServiceId(msg, LongJobConstants.SERVICE_ID);
    bus.send(msg, new CloudBusCallBack(submitCallBack) {
        @Override
        public void run(MessageReply reply) {
            if (!reply.isSuccess()) {
                longJobCallBacks.remove(apiId);
            }

            if (submitCallBack != null) {
                submitCallBack.run(reply);
            }
        }
    });
}
 
Example #12
Source Project: logging-log4j-audit   Author: apache   File: TransferTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testValidationFailureForMissingRequestContextAttribute() {
 MutableBoolean exceptionHandled = new MutableBoolean(false);
 LogEventFactory.setDefaultHandler((message, ex) -> {
  assertThat(ex, instanceOf(ConstraintValidationException.class));
  exceptionHandled.setTrue();
 });

    Transfer transfer = LogEventFactory.getEvent(Transfer.class);
    ThreadContext.put("companyId", "12345");
    ThreadContext.put("ipAddress", "127.0.0.1");
    ThreadContext.put("environment", "dev");
    ThreadContext.put("product", "TestProduct");
    ThreadContext.put("timeZone", "America/Phoenix");
    ThreadContext.put("loginId", "TestUser");
    transfer.setToAccount(123456);
    transfer.setFromAccount(111111);
    transfer.setAmount(new BigDecimal(111.55));
    transfer.logEvent();

 assertTrue("Should have thrown a ConstraintValidationException", exceptionHandled.isTrue());
}
 
Example #13
Source Project: logging-log4j-audit   Author: apache   File: TransferTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testValidationFailureForMissingEventAttribute() {
 MutableBoolean exceptionHandled = new MutableBoolean(false);
 LogEventFactory.setDefaultHandler((message, ex) -> {
  assertThat(ex, instanceOf(ConstraintValidationException.class));
  exceptionHandled.setTrue();
 });

    Transfer transfer = LogEventFactory.getEvent(Transfer.class);
    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");
    transfer.setToAccount(123456);
    transfer.setFromAccount(111111);
    transfer.logEvent();

 assertTrue("Should have thrown a ConstraintValidationException", exceptionHandled.isTrue());
}
 
Example #14
Source Project: logging-log4j2   Author: apache   File: ContextStackJsonAttributeConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ThreadContext.ContextStack convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }

    List<String> list;
    try {
        list = ContextMapJsonAttributeConverter.OBJECT_MAPPER.readValue(s, new TypeReference<List<String>>() { });
    } catch (final IOException e) {
        throw new PersistenceException("Failed to convert JSON string to list for stack.", e);
    }

    final DefaultThreadContextStack result = new DefaultThreadContextStack(true);
    result.addAll(list);
    return result;
}
 
Example #15
Source Project: DataDefender   Author: armenak   File: DataDefender.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {

        ThreadContext.put("console-level", "");
        ThreadContext.put("file-level", "");

        CommandLine cmd = new CommandLine(new DataDefender())
            .registerConverter(Requirement.class, new RequirementConverter())
            .setParameterExceptionHandler(new ShortErrorMessageHandler());
        int exitCode = cmd.execute(args);
        System.exit(exitCode);
    }
 
Example #16
Source Project: logging-log4j2   Author: apache   File: ThreadContextBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
static Map<String, String> createMap(final List<Property> properties) {
    final Map<String, String> contextMap = ThreadContext.getImmutableContext();
    if (properties == null || properties.isEmpty()) {
        return contextMap; // may be ThreadContext.EMPTY_MAP but not null
    }
    final Map<String, String> map = new HashMap<>(contextMap);

    for (final Property prop : properties) {
        if (!map.containsKey(prop.getName())) {
            map.put(prop.getName(), prop.getValue());
        }
    }
    return Collections.unmodifiableMap(map);
}
 
Example #17
Source Project: zstack   Author: zstackio   File: CreateDataVolumeTemplateFromVolumeLongJob.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start(LongJobVO job, ReturnValueCompletion<APIEvent> completion) {
    CreateDataVolumeTemplateFromVolumeMsg msg = JSONObjectUtil.toObject(job.getJobData(), CreateDataVolumeTemplateFromVolumeMsg.class);
    if (msg.getResourceUuid() == null) {
        msg.setResourceUuid(Platform.getUuid());
        job.setJobData(JSONObjectUtil.toJsonString(msg));
        dbf.updateAndRefresh(job);
    }
    bus.makeLocalServiceId(msg, ImageConstant.SERVICE_ID);
    bus.send(msg, new CloudBusCallBack(completion) {
        @Override
        public void run(MessageReply reply) {
            if (reply.isSuccess()) {
                CreateDataVolumeTemplateFromVolumeReply r = reply.castReply();
                APICreateDataVolumeTemplateFromVolumeEvent evt = new APICreateDataVolumeTemplateFromVolumeEvent(ThreadContext.get(Constants.THREAD_CONTEXT_API));

                auditResourceUuid = r.getInventory().getUuid();
                evt.setInventory(r.getInventory());

                if (jobCanceled(job.getUuid())) {
                    deleteAfterCancel(r.getInventory(), job, completion);
                } else {
                    completion.success(evt);
                }
            } else {
                auditResourceUuid = msg.getResourceUuid();
                completion.fail(reply.getError());
            }
        }
    });
}
 
Example #18
Source Project: chronus   Author: 360jinrong   File: ContextLog4j2Util.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将上下文环境变量信息加入到ThreadContext中,以便打印到日志
 */
public static void addContext2ThreadContext() {
    ServiceContext context = ServiceContext.getContext();
    if (context == null) {
        log.warn("上下文未处理化,context is null");
        return;
    }
    ThreadContext.put(ContextConstKey.REQUEST_NO, StringUtils.isEmpty(context.getRequestNo()) ? "" : context.getRequestNo());
    ThreadContext.put(ContextConstKey.SYS_CODE, StringUtils.isEmpty(context.getSysCode()) ? "" : context.getSysCode());
    ThreadContext.put(ContextConstKey.LOCAL_IP, NetUtils.getLocalIP());
    ThreadContext.put(ContextConstKey.BEAN_NAME, StringUtils.isEmpty(context.getBeanName()) ? "" : context.getBeanName());
}
 
Example #19
Source Project: logging-log4j2   Author: apache   File: Log4j1NdcPatternConverterTest.java    License: 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 #20
Source Project: logging-log4j2   Author: apache   File: ThreadContextDataInjectorTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testContextDataInjector() {
    ReadOnlyThreadContextMap readOnlythreadContextMap = getThreadContextMap();
    assertThat("thread context map class name",
               (readOnlythreadContextMap == null) ? null : readOnlythreadContextMap.getClass().getName(),
               is(equalTo(readOnlythreadContextMapClassName)));

    ContextDataInjector contextDataInjector = createInjector();
    StringMap stringMap = contextDataInjector.injectContextData(null, new SortedArrayStringMap());

    assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
    assertThat("context map", stringMap.toMap(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));

    if (!stringMap.isFrozen()) {
        stringMap.clear();
        assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
        assertThat("context map", stringMap.toMap().entrySet(), is(empty()));
    }

    ThreadContext.put("foo", "bum");
    ThreadContext.put("baz", "bam");

    assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bum"), hasEntry("baz", "bam")));
    if (stringMap.isFrozen()) {
        assertThat("context map", stringMap.toMap(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
    } else {
        assertThat("context map", stringMap.toMap().entrySet(), is(empty()));
    }
}
 
Example #21
Source Project: audit-log-plugin   Author: jenkinsci   File: RequestContext.java    License: 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 #22
Source Project: logging-log4j2   Author: apache   File: ThreadContextDataInjector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ReadOnlyStringMap rawContextData() {
    final ReadOnlyThreadContextMap map = ThreadContext.getThreadContextMap();
    if (map instanceof ReadOnlyStringMap) {
        return (ReadOnlyStringMap) map;
    }
    // note: default ThreadContextMap is null
    final Map<String, String> copy = ThreadContext.getImmutableContext();
    return copy.isEmpty() ? ContextDataFactory.emptyFrozenContextData() : new JdkMapAdapterStringMap(copy);
}
 
Example #23
Source Project: logging-log4j2   Author: apache   File: YamlLayoutTest.java    License: 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 #24
Source Project: pulsar   Author: apache   File: TimeTriggerPolicy.java    License: Apache License 2.0 5 votes vote down vote up
private Runnable newTriggerTask() {
    return new Runnable() {
        @Override
        public void run() {
            // initialize the thread context
            ThreadContext.put("function", WindowUtils.getFullyQualifiedName(
                    context.getTenant(), context.getNamespace(), context.getFunctionName()));
            // do not process current timestamp since tuples might arrive while the trigger is executing
            long now = System.currentTimeMillis() - 1;
            try {
                /*
                 * set the current timestamp as the reference time for the eviction policy
                 * to evict the events
                 */
                evictionPolicy.setContext(new DefaultEvictionContext(now, null, null, duration));
                handler.onTrigger();
            } catch (Throwable th) {
                log.error("handler.onTrigger failed ", th);
                /*
                 * propagate it so that task gets canceled and the exception
                 * can be retrieved from executorFuture.get()
                 */
                throw th;
            }
        }
    };
}
 
Example #25
Source Project: zstack   Author: zstackio   File: LongJobManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Long getApiTimeout() {
    String type = ThreadContext.get(Constants.THREAD_CONTEXT_TASK_NAME);
    if (type != null && longJobClasses.contains(type)) {
        Class<? extends APIMessage> batchJobFor = useApiTimeout.get(type);
        if (batchJobFor != null) {
            return getMessageTimeout(batchJobFor);
        }

        // default input unit is second should be changed to millis
        return TimeUnit.SECONDS.toMillis(LongJobGlobalConfig.LONG_JOB_DEFAULT_TIMEOUT.value(Long.class));
    }

    return null;
}
 
Example #26
Source Project: pinpoint   Author: naver   File: LogEventFactoryInterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void interceptorTest2() {
    TraceContext traceContext = spy(TraceContext.class);
    Trace trace = mock(Trace.class);
    TraceId traceId = spy(TraceId.class);
    when(traceContext.currentTraceObject()).thenReturn(trace);
    when(traceContext.currentRawTraceObject()).thenReturn(trace);
    when(traceContext.currentRawTraceObject().getTraceId()).thenReturn(traceId);
    when(traceContext.currentRawTraceObject().getTraceId().getTransactionId()).thenReturn("aaa");
    when(traceContext.currentRawTraceObject().getTraceId().getSpanId()).thenReturn(112343l);
    LogEventFactoryInterceptor interceptor = spy(new LogEventFactoryInterceptor(traceContext));
    interceptor.before(null);
    interceptor.after(null, null, null);
    Assert.assertTrue(ThreadContext.get(TRANSACTION_ID) != null);
}
 
Example #27
Source Project: aws-xray-sdk-java   Author: aws   File: Log4JSegmentListenerTest.java    License: 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 #28
Source Project: aws-xray-sdk-java   Author: aws   File: Log4JSegmentListenerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetPrefix() {
    Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
    listener.setPrefix("");
    Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID);

    listener.onSetEntity(null, seg);

    Assert.assertEquals(TRACE_ID.toString() + "@" + seg.getId(), ThreadContext.get(TRACE_ID_KEY));
}
 
Example #29
Source Project: aws-xray-sdk-java   Author: aws   File: Log4JSegmentListenerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsampledSegmentInjection() {
    Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
    listener.setPrefix("");
    Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID);
    seg.setSampled(false);
    listener.onSetEntity(null, seg);

    Assert.assertNull(ThreadContext.get(TRACE_ID_KEY));
}
 
Example #30
Source Project: zstack   Author: zstackio   File: LongJobApiInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private LongJobVO createSuccessLongJob(APISubmitLongJobMsg msg) {
    // create LongJobVO
    LongJobVO vo = new LongJobVO();
    if (msg.getResourceUuid() != null) {
        vo.setUuid(msg.getResourceUuid());
    } else {
        vo.setUuid(Platform.getUuid());
    }
    if (msg.getName() != null) {
        vo.setName(msg.getName());
    } else {
        vo.setName(msg.getJobName());
    }
    vo.setDescription(msg.getDescription());
    vo.setApiId(ThreadContext.getImmutableContext().get(Constants.THREAD_CONTEXT_API));
    vo.setJobName(msg.getJobName());
    vo.setJobData(msg.getJobData());
    vo.setState(LongJobState.Succeeded);
    vo.setJobResult(LongJobUtils.succeeded);
    vo.setTargetResourceUuid(msg.getTargetResourceUuid());
    vo.setManagementNodeUuid(Platform.getManagementServerId());
    vo.setAccountUuid(msg.getSession().getAccountUuid());
    vo = dbf.persistAndRefresh(vo);
    msg.setJobUuid(vo.getUuid());
    tagMgr.createTags(msg.getSystemTags(), msg.getUserTags(), vo.getUuid(), LongJobVO.class.getSimpleName());

    return vo;
}