org.slf4j.MDC Java Examples
The following examples show how to use
org.slf4j.MDC.
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: BiConsumerWithTracingTest.java From wingtips with Apache License 2.0 | 6 votes |
@Before public void beforeMethod() { biConsumerMock = mock(BiConsumer.class); inObj1 = new Object(); inObj2 = new Object(); throwExceptionDuringCall = false; currentSpanStackWhenBiConsumerWasCalled = new ArrayList<>(); currentMdcInfoWhenBiConsumerWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenBiConsumerWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenBiConsumerWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(biConsumerMock).accept(inObj1, inObj2); resetTracing(); }
Example #2
Source File: BaseInboundHandlerWithTracingAndMdcSupportTest.java From riposte with Apache License 2.0 | 6 votes |
@Test public void linkTracingAndMdcToCurrentThread_should_set_tracing_and_mdc_to_state_values_if_available() { // given Map<String, String> stateMdcInfo = new HashMap<>(); stateMdcInfo.put("foo", "bar"); Deque<Span> stateTraceStack = new LinkedList<>(); Span span = Span.generateRootSpanForNewTrace("fooSpanName", LOCAL_ONLY).withTraceId("fooTraceId").build(); stateTraceStack.add(span); state.setLoggerMdcContextMap(stateMdcInfo); state.setDistributedTraceStack(stateTraceStack); assertThat(MDC.getCopyOfContextMap().isEmpty(), is(true)); assertThat(Tracer.getInstance().getCurrentSpan(), nullValue()); // when handler.linkTracingAndMdcToCurrentThread(ctxMock); // then // Tracer adds some stuff to the MDC stateMdcInfo.put(SpanFieldForLoggerMdc.TRACE_ID.mdcKey, span.getTraceId()); assertThat(MDC.getCopyOfContextMap(), is(stateMdcInfo)); assertThat(Tracer.getInstance().getCurrentSpanStackCopy(), is(stateTraceStack)); }
Example #3
Source File: MiddlewaresTest.java From styx with Apache License 2.0 | 6 votes |
@Test public void testExceptionAndRequestIdHandlerAcceptsRequestIdHeader() throws InterruptedException, ExecutionException, TimeoutException { final RequestContext requestContext = mock(RequestContext.class); final String requestId = UUID.randomUUID().toString(); final Request request = Request.forUri("/", "GET") .withHeader("X-Request-Id", requestId); final AtomicReference<String> propagatedRequestId = new AtomicReference<>(); when(requestContext.request()).thenReturn(request); Response<Object> response = Middlewares.exceptionAndRequestIdHandler() .apply(rc -> { propagatedRequestId.set(MDC.get("request-id")); LoggerFactory.getLogger(MiddlewaresTest.class).info("I'm OK!"); return completedFuture(Response.forStatus(Status.OK)); }) .invoke(requestContext) .toCompletableFuture().get(5, SECONDS); assertThat(response, hasStatus(withCode(Status.OK))); assertThat(response, hasHeader("X-Request-Id", is(requestId))); assertThat(propagatedRequestId.get(), is(requestId)); }
Example #4
Source File: Server.java From light-4j with Apache License 2.0 | 6 votes |
public static void init() { logger.info("server starts"); // setup system property to redirect undertow logs to slf4j/logback. System.setProperty("org.jboss.logging.provider", "slf4j"); try { loadConfigs(); // this will make sure that all log statement will have serviceId MDC.put(SID, config.getServiceId()); // merge status.yml and app-status.yml if app-status.yml is provided mergeStatusConfig(); start(); } catch (RuntimeException e) { // Handle any exception encountered during server start-up logger.error("Server is not operational! Failed with exception", e); System.out.println("Failed to start server:" + e.getMessage()); // send a graceful system shutdown System.exit(1); } }
Example #5
Source File: TestSessionManager.java From HttpSessionReplacer with MIT License | 6 votes |
@Test public void testDisableSessionInMdc() { MDC.remove(configuration.getLoggingMdcKey()); configuration.setLoggingMdcActive(false); SessionData sessionData = new SessionData("1", now(), 10); RepositoryBackedSession session = mock(RepositoryBackedSession.class); when(session.getId()).thenReturn("1"); when(repository.getSessionData("1")).thenReturn(sessionData); when(factory.build(sessionData)).thenReturn(session); RequestWithSession request = mock(RequestWithSession.class); when(tracking.retrieveId(request)).thenReturn(new SessionTracking.IdAndSource("1", false)); sessionManager.getSession(request, false, null); assertNull("Logging MDC should remain null", MDC.get(configuration.getLoggingMdcKey())); MDC.put(configuration.getLoggingMdcKey(), "something"); sessionManager.getSession(request, false, null); assertEquals("Logging MDC was changed", "something", MDC.get(configuration.getLoggingMdcKey())); request = mock(RequestWithSession.class); sessionManager.getSession(request, false, null); assertEquals("Logging MDC was changed", "something", MDC.get(configuration.getLoggingMdcKey())); }
Example #6
Source File: DefaultPropertiesConverterTest.java From cf-java-logging-support with Apache License 2.0 | 6 votes |
@Test public void properlyEscapesExclusions() throws Exception { StringBuilder sb = new StringBuilder(); @SuppressWarnings("serial") Map<String, String> explicitFields = new HashMap<String, String>() { { put("explicit" + HACK_ATTEMPT, "explicit value"); } }; MDC.put("mdc" + HACK_ATTEMPT, "mdc value"); converter.setExclusions(Arrays.asList("explicit" + HACK_ATTEMPT, "mdc" + HACK_ATTEMPT)); converter.convert(sb, explicitFields); assertThat(unmarshal(sb), allOf(not(hasEntry("mdc" + HACK_ATTEMPT, "mdc value")), not(hasEntry("explicit" + HACK_ATTEMPT, "explicit value")))); }
Example #7
Source File: DefaultPropertiesConverterTest.java From cf-java-logging-support with Apache License 2.0 | 6 votes |
@Test public void properlyEscapesValues() throws Exception { StringBuilder sb = new StringBuilder(); @SuppressWarnings("serial") Map<String, String> explicitFields = new HashMap<String, String>() { { put("explicit key", "explicit" + HACK_ATTEMPT); } }; MDC.put("mdc key", "mdc" + HACK_ATTEMPT); converter.convert(sb, explicitFields); assertThat(unmarshal(sb), allOf(hasEntry("mdc key", "mdc" + HACK_ATTEMPT), hasEntry("explicit key", "explicit" + HACK_ATTEMPT))); }
Example #8
Source File: ClusterReconciliationOrchestrator.java From rabbitmq-operator with Apache License 2.0 | 6 votes |
public void queueReconciliation(final Reconciliation reconciliation, final Consumer<Reconciliation> runner) { log.info("Queueing reconciliation {}", reconciliation); executor.submit(reconciliation.getClusterName(), reconciliation.getType(), () -> { MDC.put("clusterName", reconciliation.getClusterName()); MDC.put("namespace", reconciliation.getNamespace()); MDC.put("resourceName", reconciliation.getResourceName()); MDC.put("type", reconciliation.getType()); try { runner.accept(reconciliation); } catch (final Throwable t) { log.error("There was an error during reconciliation that the reconciler didn't handle", t); } finally { MDC.remove("type"); MDC.remove("resourceName"); MDC.remove("namespace"); MDC.remove("clusterName"); } }); log.info("Reconciliation {} successfully queued", reconciliation); }
Example #9
Source File: ConsumerWithTracingTest.java From wingtips with Apache License 2.0 | 6 votes |
@Before public void beforeMethod() { consumerMock = mock(Consumer.class); inObj = new Object(); throwExceptionDuringCall = false; currentSpanStackWhenConsumerWasCalled = new ArrayList<>(); currentMdcInfoWhenConsumerWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenConsumerWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenConsumerWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(consumerMock).accept(inObj); resetTracing(); }
Example #10
Source File: ProxyUserValidation.java From gcp-token-broker with Apache License 2.0 | 6 votes |
public static void validateImpersonator(String impersonator, String impersonated) { String mappedImpersonated = AbstractUserMapper.getInstance().map(impersonated); EmailValidation.validateEmail(mappedImpersonated); MDC.put(LoggingUtils.MDC_AUTH_MODE_PROXY_IMPERSONATED_USER_KEY, impersonated); List<? extends Config> proxyConfigs = AppSettings.getInstance().getConfigList(AppSettings.PROXY_USERS); for (Config proxyConfig : proxyConfigs) { String proxy = proxyConfig.getString(CONFIG_PROXY); if (impersonator.equals(proxy)) { if (isWhitelistedByUsername(proxyConfig, mappedImpersonated)) { // The user is directly whitelisted by its username return; } else if (isWhitelistedByGroupMembership(proxyConfig, mappedImpersonated)) { // The user is whitelisted by group membership return; } } } throw Status.PERMISSION_DENIED .withDescription("Impersonation disallowed for `" + impersonator + "`") .asRuntimeException(); }
Example #11
Source File: SolrLogLayout.java From lucene-solr with Apache License 2.0 | 6 votes |
private void appendMDC(StringBuilder sb) { if (!StringUtils.isEmpty(MDC.get(NODE_NAME_PROP))) { sb.append(" n:").append(MDC.get(NODE_NAME_PROP)); } if (!StringUtils.isEmpty(MDC.get(COLLECTION_PROP))) { sb.append(" c:").append(MDC.get(COLLECTION_PROP)); } if (!StringUtils.isEmpty(MDC.get(SHARD_ID_PROP))) { sb.append(" s:").append(MDC.get(SHARD_ID_PROP)); } if (!StringUtils.isEmpty(MDC.get(REPLICA_PROP))) { sb.append(" r:").append(MDC.get(REPLICA_PROP)); } if (!StringUtils.isEmpty(MDC.get(CORE_NAME_PROP))) { sb.append(" x:").append(MDC.get(CORE_NAME_PROP)); } }
Example #12
Source File: YuGongController.java From yugong with GNU General Public License v2.0 | 6 votes |
@Override public void stop() { super.stop(); for (YuGongInstance instance : instances) { if (instance.isStart()) { instance.stop(); } } schedule.shutdownNow(); MDC.remove(YuGongConstants.MDC_TABLE_SHIT_KEY); progressTracer.print(true); if (dataSourceFactory.isStart()) { dataSourceFactory.stop(); } MDC.remove(YuGongConstants.MDC_TABLE_SHIT_KEY); }
Example #13
Source File: ProjectServiceImpl.java From webanno with Apache License 2.0 | 6 votes |
@Override @Transactional public void createProject(Project aProject) throws IOException { if (aProject.getId() != null) { throw new IllegalArgumentException("Project has already been created before."); } aProject.setCreated(new Date()); entityManager.persist(aProject); try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID, String.valueOf(aProject.getId()))) { log.info("Created project [{}]({})", aProject.getName(), aProject.getId()); } String path = repositoryProperties.getPath().getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId(); FileUtils.forceMkdir(new File(path)); applicationEventPublisher.publishEvent(new AfterProjectCreatedEvent(this, aProject)); }
Example #14
Source File: MDCConcurrentCallable.java From Mastering-Microservices-with-Java-9-Second-Edition with MIT License | 6 votes |
@Override public K call() throws Exception { LOG.debug("Call using MDCHystrixContextCallable..."); Map childMDC = MDC.getCopyOfContextMap(); LOG.debug("childMDC --> " + childMDC); try { if (parentMDC != null) { MDC.setContextMap(parentMDC); } LOG.debug("parentMDC --> " + parentMDC); return actual.call(); } finally { if (childMDC != null) { MDC.setContextMap(childMDC); } } }
Example #15
Source File: FunctionWithTracingTest.java From wingtips with Apache License 2.0 | 6 votes |
@DataProvider(value = { "true", "false" }) @Test public void current_thread_info_constructor_sets_fields_as_expected(boolean useStaticFactory) { // given Tracer.getInstance().startRequestWithRootSpan("request-" + UUID.randomUUID().toString()); Deque<Span> spanStackMock = Tracer.getInstance().getCurrentSpanStackCopy(); Map<String, String> mdcInfoMock = MDC.getCopyOfContextMap(); // when FunctionWithTracing instance = (useStaticFactory) ? withTracing(functionMock) : new FunctionWithTracing(functionMock); // then assertThat(instance.origFunction).isSameAs(functionMock); assertThat(instance.spanStackForExecution).isEqualTo(spanStackMock); assertThat(instance.mdcContextMapForExecution).isEqualTo(mdcInfoMock); }
Example #16
Source File: AbstractTask.java From govpay with GNU General Public License v3.0 | 6 votes |
protected IContext initBatchContext(boolean setContext) throws UtilsException { GpContextFactory factory = new GpContextFactory(); IContext ctx = factory.newBatchContext(); MDC.put(MD5Constants.OPERATION_ID, this.name); MDC.put(MD5Constants.TRANSACTION_ID, ctx.getTransactionId()); Service service = new Service(); service.setName(CostantiTask.SERVICE_NAME_TASK); service.setType(GpContext.TIPO_SERVIZIO_GOVPAY_OPT); ctx.getApplicationContext().getTransaction().setService(service); Operation opt = new Operation(); opt.setName(this.name); ctx.getApplicationContext().getTransaction().setOperation(opt); if(setContext) ContextThreadLocal.set(ctx); return ctx; }
Example #17
Source File: CallContext.java From cosmic with Apache License 2.0 | 6 votes |
protected static CallContext register(final User callingUser, final Account callingAccount, final Long userId, final Long accountId, final String contextId) { /* Unit tests will have multiple times of setup/tear-down call to this, remove assertions to all unit test to run assert s_currentContext.get() == null : "There's a context already so what does this new register context mean? " + s_currentContext.get().toString(); if (s_currentContext.get() != null) { // FIXME: This should be removed soon. I added this check only to surface all the places that have this problem. throw new CloudRuntimeException("There's a context already so what does this new register context mean? " + s_currentContext.get().toString()); } */ CallContext callingContext = null; if (userId == null || accountId == null) { callingContext = new CallContext(callingUser, callingAccount, contextId); } else { callingContext = new CallContext(userId, accountId, contextId); } s_currentContext.set(callingContext); MDC.put("ctx", " (ctx: " + UuidUtils.first(contextId) + ")"); if (s_logger.isTraceEnabled()) { s_logger.trace("Registered: " + callingContext); } s_currentContextStack.get().push(callingContext); return callingContext; }
Example #18
Source File: CallableWithTracingTest.java From wingtips with Apache License 2.0 | 6 votes |
@Before public void beforeMethod() throws Exception { callableMock = mock(Callable.class); throwExceptionDuringCall = false; currentSpanStackWhenCallableWasCalled = new ArrayList<>(); currentMdcInfoWhenCallableWasCalled = new ArrayList<>(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { currentSpanStackWhenCallableWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenCallableWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; } }).when(callableMock).call(); resetTracing(); }
Example #19
Source File: DirectoryAdapter.java From emissary with Apache License 2.0 | 6 votes |
public boolean inboundAddPlaces(final HttpServletRequest req, final String dir) { if (disableAddPlaces) { return true; } else { final AddPlacesRequestBean bean = new AddPlacesRequestBean(req); final IRemoteDirectory directory = getLocalDirectory(dir); if (directory == null) { throw new IllegalArgumentException("No directory found using name " + dir); } MDC.put(MDCConstants.SERVICE_LOCATION, KeyManipulator.getServiceLocation(directory.getKey())); try { directory.irdAddPlaces(bean.getEntries(), bean.isPropagating()); } finally { MDC.remove(MDCConstants.SERVICE_LOCATION); } return true; } }
Example #20
Source File: TransLoggerService4File.java From framework with Apache License 2.0 | 6 votes |
/** * Description: <br> * * @author 王伟<br> * @taskId <br> * @param stackId * @param parentStackId * @param beginTime * @param method * @param params <br> */ @Override public void before(final String stackId, final String parentStackId, final long beginTime, final String method, final Object[] params) { if (this.isAlwaysLog()) { MDC.put("stackId", stackId); MDC.put("parentStackId", parentStackId); MDC.put("method", method); MDC.put("params", Arrays.toString(params)); logger.info("BEFORE"); MDC.clear(); } else { super.before(stackId, parentStackId, beginTime, method, params); } }
Example #21
Source File: AsyncNettyHelperTest.java From riposte with Apache License 2.0 | 6 votes |
@Test public void linkTracingAndMdcToCurrentThread_pair_works_as_expected_with_non_null_pair_and_null_innards() { // given Pair<Deque<Span>, Map<String, String>> infoForLinking = Pair.of(null, null); resetTracingAndMdc(); Tracer.getInstance().startRequestWithRootSpan("foo-" + UUID.randomUUID().toString()); Pair<Deque<Span>, Map<String, String>> expectedPreCallInfo = Pair.of( Tracer.getInstance().getCurrentSpanStackCopy(), MDC.getCopyOfContextMap() ); // when Pair<Deque<Span>, Map<String, String>> preCallInfo = AsyncNettyHelper.linkTracingAndMdcToCurrentThread(infoForLinking); Pair<Deque<Span>, Map<String, String>> postCallInfo = Pair.of( Tracer.getInstance().getCurrentSpanStackCopy(), MDC.getCopyOfContextMap() ); // then assertThat(preCallInfo).isEqualTo(expectedPreCallInfo); assertThat(postCallInfo).isEqualTo(Pair.of(null, Collections.emptyMap())); }
Example #22
Source File: DocumentServiceImpl.java From webanno with Apache License 2.0 | 6 votes |
@Override @Transactional public void createAnnotationDocument(AnnotationDocument aAnnotationDocument) { Validate.notNull(aAnnotationDocument, "Annotation document must be specified"); if (isNull(aAnnotationDocument.getId())) { entityManager.persist(aAnnotationDocument); try (MDC.MDCCloseable closable = MDC.putCloseable(Logging.KEY_PROJECT_ID, String.valueOf(aAnnotationDocument.getProject().getId()))) { log.info( "Created annotation document [{}] for user [{}] for source document " + "[{}]({}) in project [{}]({})", aAnnotationDocument.getId(), aAnnotationDocument.getUser(), aAnnotationDocument.getDocument().getName(), aAnnotationDocument.getDocument().getId(), aAnnotationDocument.getProject().getName(), aAnnotationDocument.getProject().getId()); } } else { entityManager.merge(aAnnotationDocument); } }
Example #23
Source File: BridgeMdcUtil.java From arcusplatform with Apache License 2.0 | 6 votes |
public static MdcContextReference captureAndInitializeContext(Session session) { MdcContextReference ref = MdcContext.captureMdcContext(); if(session == null) { return ref; } String place = session.getActivePlace(); String principal = session.getClient() != null ? session.getClient().getPrincipalName() : null; String type = session.getClientType(); String version = session.getClientVersion(); if(!StringUtils.isEmpty(place)) { MDC.put(MdcContext.MDC_PLACE, place); } if(!StringUtils.isEmpty(principal)) { MDC.put(MdcContext.MDC_TARGET, principal); } if(StringUtils.isEmpty(version)) { version = "unknown"; } MDC.put(MdcContext.MDC_CLIENT_VERSION, type + " " + version); return ref; }
Example #24
Source File: BiConsumerWithTracingAndMdcSupportTest.java From riposte with Apache License 2.0 | 5 votes |
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); consumerMock = mock(BiConsumer.class); inObj1 = new Object(); inObj2 = new Object(); throwExceptionDuringCall = false; currentSpanStackWhenBiConsumerWasCalled = new ArrayList<>(); currentMdcInfoWhenBiConsumerWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenBiConsumerWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenBiConsumerWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(consumerMock).accept(inObj1, inObj2); resetTracingAndMdc(); }
Example #25
Source File: ErrorToElasticsearchProcessor.java From SkaETL with Apache License 2.0 | 5 votes |
@Override protected void parseResultErrors(BulkRequest request, BulkResponse bulkItemResponses) { for (BulkItemResponse bir : bulkItemResponses) { MDC.put("item_error", bir.getFailureMessage()); log.info("EsError" + bir.getFailureMessage()); MDC.remove("item_error"); //TODO ... } }
Example #26
Source File: HttpMockServiceImpl.java From AnyMock with Apache License 2.0 | 5 votes |
@Override public void mock(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpMockContext context = new HttpMockContext(); // 加载HTTP接口数据 HttpInterfaceKeyBO httpInterfaceKeyBO = new HttpInterfaceKeyBO(); httpInterfaceKeyBO.setRequestMethod(request.getMethod()); httpInterfaceKeyBO.setRequestUri(request.getRequestURI()); context.setHttpInterfaceBO(loadHttpInterfaceBO(httpInterfaceKeyBO)); // 由于输入流能且仅能读取一次,而后续可能多次调用,因此需要临时存储 request.setAttribute(BODY, buildHttpBody(request)); if (logger.isInfoEnabled()) { logger.info("\n################### HTTP REQUEST ###################\n" + buildRawHttpMsg(request) + "\n####################################################"); } // 同步 httpSyncMockService.mock(context, request, response); // 异步 if (BooleanUtils.isTrue(context.getHttpInterfaceBO().getNeedAsyncCallback())) { String mdcTraceId = MDC.get(MdcManager.MDC_TRACE_ID_KEY); MockHttpServletRequest mockRequest = buildMockRequest(request); threadPoolTaskExecutor.execute(() -> { try { MDC.put(MdcManager.MDC_TRACE_ID_KEY, mdcTraceId); httpAsyncMockService.mock(context, mockRequest); MDC.clear(); } catch (Exception e) { logger.warn("", e); } }); } }
Example #27
Source File: RunnableWithTracingAndMdcSupportTest.java From riposte with Apache License 2.0 | 5 votes |
@DataProvider(value = { "true", "false" }) @Test public void run_handles_tracing_and_mdc_info_as_expected(boolean throwException) { // given throwExceptionDuringCall = throwException; Tracer.getInstance().startRequestWithRootSpan("foo"); Deque<Span> spanStack = Tracer.getInstance().getCurrentSpanStackCopy(); Map<String, String> mdcInfo = MDC.getCopyOfContextMap(); RunnableWithTracingAndMdcSupport instance = new RunnableWithTracingAndMdcSupport( runnableMock, spanStack, mdcInfo ); resetTracingAndMdc(); assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull(); assertThat(MDC.getCopyOfContextMap()).isEmpty(); // when Throwable ex = catchThrowable(() -> instance.run()); // then verify(runnableMock).run(); if (throwException) assertThat(ex).isNotNull(); else assertThat(ex).isNull(); assertThat(currentSpanStackWhenRunnableWasCalled.get(0)).isEqualTo(spanStack); assertThat(currentMdcInfoWhenRunnableWasCalled.get(0)).isEqualTo(mdcInfo); assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull(); assertThat(MDC.getCopyOfContextMap()).isEmpty(); }
Example #28
Source File: TestController.java From log-trace-spring-boot with Apache License 2.0 | 5 votes |
@GetMapping("test") public String test() { MDC.put("test", String.valueOf(Math.random())); log.info("controller test 执行 {}", MDC.get("test")); testService.test(); return "test"; }
Example #29
Source File: TraceContentFactory.java From log-trace-spring-boot with Apache License 2.0 | 5 votes |
/** * 获取 MDC 内容 同时添加 X-B3-ParentName 参数 * * @return MDC map */ private static Map<String, String> buildTraceContent() { Map<String, String> traceContentMap = MDC.getCopyOfContextMap(); if (traceContentMap == null) { traceContentMap = new HashMap<>(16); } String serviceName = environment.getProperty("spring.application.name"); traceContentMap.put(Constants.LEGACY_PARENT_SERVICE_NAME, serviceName); return traceContentMap; }
Example #30
Source File: ProgressTaskLoggerMDCTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testMDCCopy() throws InterruptedException { String mainThread = Thread.currentThread().getName(); // put something into MDC in current thread MDC.put("foo", "bar"); // since we are testing with threads, we need to track that the inner thread ran through AtomicBoolean tested = new AtomicBoolean(false); // create progress task logger with 1ms start delay (i.e. start immediately). Interval is not relevant for this test. ProgressTaskLogger progressTaskLogger = new ProgressTaskLogger(mockLogger, 1, 60000, TimeUnit.MILLISECONDS) { void logProgress() { super.logProgress(); assertThat(mainThread, not(equalTo(Thread.currentThread().getName()))); // verify we are in a different thread assertThat(MDC.get("foo"), equalTo("bar")); tested.set(true); } }; // store a progress message before start so it is there immediately progressTaskLogger.progress(new TaskLoggingEvent(mockLogger, "test message")); progressTaskLogger.start(); Thread.sleep(100); // wait for the execution to complete // assert that the test ran assertTrue(tested.get()); progressTaskLogger.finish(); }