org.apache.logging.log4j.ThreadContext Java Examples

The following examples show how to use org.apache.logging.log4j.ThreadContext. 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 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 #2
Source File: LogbackIntegrationTest.java    From sofa-common-tools with 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 #3
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 #4
Source File: RevertVolumeSnapshotLongJob.java    From zstack with 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 #5
Source File: LongJobManagerImpl.java    From zstack with 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 #6
Source File: CephPrimaryStorageBase.java    From zstack with 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 #7
Source File: AsyncLogger.java    From logging-log4j2 with 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 File: GelfLayoutTest3.java    From logging-log4j2 with 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 #9
Source File: ThreadContextUtilityClass.java    From logging-log4j2 with 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 #10
Source File: TransferTest.java    From logging-log4j-audit with 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 #11
Source File: TransferTest.java    From logging-log4j-audit with 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 #12
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 #13
Source File: ContextStackJsonAttributeConverter.java    From logging-log4j2 with 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 #14
Source File: StrSubstitutorTest.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));
    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 #15
Source File: ThreadContextStackResolver.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void resolve(
        final LogEvent logEvent,
        final JsonWriter jsonWriter) {
    final ThreadContext.ContextStack contextStack = logEvent.getContextStack();
    if (contextStack.getDepth() == 0) {
        jsonWriter.writeNull();
        return;
    }
    boolean arrayStarted = false;
    for (final String contextStackItem : contextStack.asList()) {
        final boolean matched =
                itemPattern == null ||
                        itemPattern.matcher(contextStackItem).matches();
        if (matched) {
            if (arrayStarted) {
                jsonWriter.writeSeparator();
            } else {
                jsonWriter.writeArrayStart();
                arrayStarted = true;
            }
            jsonWriter.writeString(contextStackItem);
        }
    }
    if (arrayStarted) {
        jsonWriter.writeArrayEnd();
    } else {
        jsonWriter.writeNull();
    }
}
 
Example #16
Source File: AuditLoggerTest.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
@Test(expected = ConstraintValidationException.class)
public void testMissingEventAttribute() {
    auditLogger = buildAuditLogger(catalogReader);

    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");
    Map<String, String> properties = new HashMap<>();
    properties.put("toAccount", "123456");
    properties.put("amount", "111.55");
    auditLogger.logEvent("transfer", properties);
}
 
Example #17
Source File: ThreadContextScopeDecoratorTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override protected void verifyImplicitContext(@Nullable TraceContext context) {
  if (context != null) {
    assertThat(ThreadContext.get("traceId")).isEqualTo(context.traceIdString());
    assertThat(ThreadContext.get("spanId")).isEqualTo(context.spanIdString());
    assertThat(ThreadContext.get(CORRELATION_FIELD.name()))
      .isEqualTo(CORRELATION_FIELD.baggageField().getValue(context));
  } else {
    assertThat(ThreadContext.get("traceId")).isNull();
    assertThat(ThreadContext.get("spanId")).isNull();
    assertThat(ThreadContext.get(CORRELATION_FIELD.name())).isNull();
  }
}
 
Example #18
Source File: Log4JSegmentListenerTest.java    From aws-xray-sdk-java with 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 #19
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 #20
Source File: ThreadContextBenchmark.java    From logging-log4j2 with 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 #21
Source File: LongJobApiInterceptor.java    From zstack with 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;
}
 
Example #22
Source File: Log4j2IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Logger logger = LogManager.getLogger();
    logger.error("for log4j2 plugin test");

    Assert.assertNotNull(ThreadContext.get("PtxId"));
    Assert.assertNotNull(ThreadContext.get("PspanId"));
}
 
Example #23
Source File: SyslogAppenderTestBase.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected void sendInfoStructuredMessage() {
    ThreadContext.put("loginId", "JohnDoe");
    ThreadContext.put("ipAddress", "192.168.0.120");
    ThreadContext.put("locale", Locale.US.getDisplayName());
    final StructuredDataMessage msg = new StructuredDataMessage("Transfer@18060", "Transfer Complete", "Audit");
    msg.put("ToAccount", "123456");
    msg.put("FromAccount", "123457");
    msg.put("Amount", "200.00");
    // the msg.toString() doesn't contain the parameters of the ThreadContext, so we must use the line1 string
    final String str = msg.asString(null, null);
    sentMessages.add(str);
    root.info(MarkerManager.getMarker("EVENT"), msg);
}
 
Example #24
Source File: RequestContext.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
public static Long getAccountNumber() {
    String value = ThreadContext.get(ACCOUNT_NUMBER);
    if (value == null || value.length() == 0) {
        return 0L;
    }
    try {
        return Long.parseLong(value);
    } catch (Exception e) {
        return 0L;
    }
}
 
Example #25
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 #26
Source File: Log4JSegmentListenerTest.java    From aws-xray-sdk-java with 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 #27
Source File: Log4j2ForAsyncLoggerIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Logger logger = LogManager.getLogger();
    logger.error("for log4j2 plugin async logger test");

    Assert.assertNotNull(ThreadContext.get("PtxId"));
    Assert.assertNotNull(ThreadContext.get("PspanId"));
}
 
Example #28
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 #29
Source File: LogEventFactoryInterceptorTest.java    From pinpoint with 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 #30
Source File: LongJobManagerImpl.java    From zstack with 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;
}