Java Code Examples for org.slf4j.MDC#setContextMap()

The following examples show how to use org.slf4j.MDC#setContextMap() . 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: MDCConcurrentCallable.java    From Mastering-Microservices-with-Java with MIT License 6 votes vote down vote up
@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 2
Source File: PoseidonConsumer.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private void setContext(PoseidonRequest request) {
    RequestContext.set(METHOD, request.getAttribute(METHOD).toString());
    RequestContext.set(SOURCE_ADDRESS, request.getUrl());

    if (configuration.getHeadersConfiguration() != null && configuration.getHeadersConfiguration().getGlobalHeaders() != null) {
        Map<String, String> headers = new HashMap<>();
        for (HeaderConfiguration headerConfiguration : configuration.getHeadersConfiguration().getGlobalHeaders()) {
            String value = request.getHeader(headerConfiguration.getName());
            if (value == null) {
                value = headerConfiguration.getDefaultValue();
            }
            if (value != null) {
                headers.put(headerConfiguration.getName(), value);
            }
        }

        ImmutableMap<String, String> immutableHeaders = ImmutableMap.copyOf(headers);
        ServiceContext.set(ServiceClientConstants.HEADERS, immutableHeaders);
        ServiceContext.set(ServiceClientConstants.COMMANDS, new ConcurrentLinkedQueue<String>());
        ServiceContext.set(ServiceClientConstants.COLLECT_COMMANDS, configuration.collectServiceClientCommandNames());
        ServiceContext.set(ServiceClientConstants.THROW_ORIGINAL, configuration.throwOriginalExceptionsForNonUpstreamFailures());
        RequestContext.set(HEADERS, immutableHeaders);
        MDC.setContextMap(immutableHeaders);
    }
}
 
Example 3
Source File: MDCConcurrentCallable.java    From Mastering-Microservices-with-Java-9-Second-Edition with MIT License 6 votes vote down vote up
@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 4
Source File: MDCConcurrentCallable.java    From Mastering-Microservices-with-Java-9-Second-Edition with MIT License 6 votes vote down vote up
@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 5
Source File: MDCConcurrentCallable.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
@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 6
Source File: MdcAwareCallable.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public V call() throws Exception {
   try(MdcContextReference ref = MdcContext.captureMdcContext()) {
      MDC.setContextMap(mdc);
      return delegate.call();
   }
}
 
Example 7
Source File: Event.java    From ci-droid with Apache License 2.0 5 votes vote down vote up
/**
 * Logs the metric using SLF4J log statement. The attributes are written into the MDC
 */
public synchronized void publish() {
    final Map<String, String> copyOfMDC = MDC.getCopyOfContextMap();

    attributes.forEach(MDC::put);
    try {
        logger.info("");
    } finally {
        if (copyOfMDC != null) {
            MDC.setContextMap(copyOfMDC);
        } else {
            MDC.clear();
        }
    }
}
 
Example 8
Source File: ServiceTalkThreadContextMapTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleExecution() {
    MDC.clear();
    assertEquals(0, MDC.getCopyOfContextMap().size());
    assertEquals("unexpected map: " + getStorage(), 0, getStorage().size());

    MDC.put("aa", "1");
    assertEquals("1", MDC.get("aa"));
    assertEquals(1, MDC.getCopyOfContextMap().size());
    assertEquals("unexpected map: " + getStorage(), 1, getStorage().size());

    MDC.put("bb", "2");
    assertEquals("2", MDC.get("bb"));
    assertEquals(2, MDC.getCopyOfContextMap().size());
    assertEquals(2, getStorage().size());

    logger.info("expected aa=1 bb=2"); // human inspection as sanity check

    MDC.remove("aa");
    assertNull(MDC.get("aa"));
    assertEquals(1, MDC.getCopyOfContextMap().size());
    assertEquals(1, getStorage().size());

    MDC.setContextMap(Collections.singletonMap("cc", "3"));
    assertNull(MDC.get("bb"));
    assertEquals("3", MDC.get("cc"));
    assertEquals(1, MDC.getCopyOfContextMap().size());
    assertEquals(1, getStorage().size());

    logger.info("expected cc=3"); // human inspection as sanity check
}
 
Example 9
Source File: ProgressTaskLogger.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@VisibleForTesting
void logProgress() {
  if (lastProgressEvent != null) {
    if (mdcMap != null) {
      MDC.setContextMap(mdcMap);
    }

    Logger logger = Optional.ofNullable(lastProgressEvent.getLogger()).orElse(log);
    logger.info(INTERNAL_PROGRESS, format(PROGRESS_LINE, lastProgressEvent.getMessage()),
        lastProgressEvent.getArgumentArray());

    // clear last progress so it does not get logged again
    lastProgressEvent = null;
  }
}
 
Example 10
Source File: AsyncConfig.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
@Override
public Runnable decorate(Runnable runnable) {
    Map<String, String> contextMap = MDC.getCopyOfContextMap();
    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            if (contextMap != null) {
                MDC.setContextMap(contextMap);
            }
            runnable.run();
        }
    };
    return runnable1;
}
 
Example 11
Source File: CopyThreadLocalCallable.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public T call() throws Exception {
  try {
    threadLocalState.propagate();
    if (currentMdcState != null) {
      MDC.setContextMap(currentMdcState);
    }
    return wrapped.call();
  } finally {
    threadLocalState.cleanup();
    MDC.clear();
  }
}
 
Example 12
Source File: AsyncWingtipsHelperJava7.java    From wingtips with Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@link Tracer#unregisterFromThread()} and {@link MDC#clear()} to reset this thread's tracing and
 * MDC state to be completely clean, then (optionally) resets the span stack and MDC info to the arguments
 * provided. If the span stack argument is null then the span stack will *not* be reset, and similarly if the MDC
 * info is null then the MDC info will *not* be reset. So if both are null then when this method finishes the trace
 * stack and MDC will be left in a blank state.
 *
 * @deprecated Please move to the Java 8 version of this class and method ({@code AsyncWingtipsHelper} or the static
 * {@code AsyncWingtipsHelperStatic}) whenever possible.
 */
@Deprecated
public static void unlinkTracingFromCurrentThread(Deque<Span> spanStackToResetFor,
                                                  Map<String, String> mdcContextMapToResetFor) {
    Tracer.getInstance().unregisterFromThread();
    MDC.clear();

    if (mdcContextMapToResetFor != null)
        MDC.setContextMap(mdcContextMapToResetFor);

    if (spanStackToResetFor != null)
        Tracer.getInstance().registerWithThread(spanStackToResetFor);
}
 
Example 13
Source File: MdcAwareCallableWrapper.java    From hystrix-context-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public T call() throws Exception {
    try {
        MDC.setContextMap(contextMap);
        return callable.call();
    } finally {
        MDC.clear();
    }
}
 
Example 14
Source File: AsyncNettyHelper.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@link Tracer#unregisterFromThread()} and {@link org.slf4j.MDC#clear()} to reset this thread's tracing and
 * MDC state to be completely clean, then (optionally) resets the trace stack and MDC info to the arguments
 * provided. If the trace stack argument is null then the trace stack will *not* be reset, and similarly if the MDC
 * info is null then the MDC info will *not* be reset. So if both are null then when this method finishes the trace
 * stack and MDC will be left in a blank state.
 */
public static void unlinkTracingAndMdcFromCurrentThread(Deque<Span> distributedTraceStackToResetFor,
                                                        Map<String, String> mdcContextMapToResetFor) {
    Tracer.getInstance().unregisterFromThread();
    MDC.clear();

    if (mdcContextMapToResetFor != null)
        MDC.setContextMap(mdcContextMapToResetFor);

    if (distributedTraceStackToResetFor != null)
        Tracer.getInstance().registerWithThread(distributedTraceStackToResetFor);
}
 
Example 15
Source File: RequestLogger.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private void generateLog() {
	Map<String, String> contextMap = getContextMap();
	Map<String, String> currentContextMap = MDC.getCopyOfContextMap();
	try {
		MDC.setContextMap(contextMap);
		LOG.info(Markers.REQUEST_MARKER, "{}", requestRecord);
	} finally {
		if (currentContextMap != null) {
			MDC.setContextMap(currentContextMap);
		}
	}
}
 
Example 16
Source File: SolrException.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public void logInfoWithMdc(Logger logger, String msg) {
  Map<String, String> previousMdcContext = MDC.getCopyOfContextMap();
  MDC.setContextMap(mdcContext);
  try {
    logger.info(msg);
  } finally{
    MDC.setContextMap(previousMdcContext);
  }
}
 
Example 17
Source File: CopyThreadLocalRunnable.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void run() {
  try {
    threadLocalState.propagate();
    if (currentMdcState != null) {
      MDC.setContextMap(currentMdcState);
    }
    wrapped.run();
  } finally {
    threadLocalState.cleanup();
    MDC.clear();
  }
}
 
Example 18
Source File: AsyncNettyHelper.java    From riposte with Apache License 2.0 4 votes vote down vote up
/**
 * Links the given distributed tracing and logging MDC info to the current thread. Any existing tracing and MDC info
 * on the current thread will be wiped out and overridden, so if you need to go back to them in the future you'll
 * need to store the copy info returned by this method for later.
 *
 * @param distributedTraceStackToLink
 *     The stack of distributed traces that should be associated with the current thread. This can be null - if it
 *     is null then {@link Tracer} will be setup with an empty trace stack (wiping out any existing in-progress
 *     traces).
 * @param mdcContextMapToLink
 *     The MDC context map to associate with the current thread. This can be null - if it is null then {@link
 *     org.slf4j.MDC#clear()} will be called (wiping out any existing MDC info).
 *
 * @return A *COPY* of the original trace stack and MDC info on the thread when this method was called (before being
 * replaced with the given arguments). The {@link Pair} object will never be null, but the values it contains may be
 * null. A copy is returned rather than the original to prevent undesired behavior (storing the return value and
 * then passing it in to {@link #unlinkTracingAndMdcFromCurrentThread(Pair)} later should *guarantee* that after
 * calling that unlink method the thread state is exactly as it was right *before* calling this link method. If we
 * returned the original trace stack this contract guarantee could be violated).
 */
public static Pair<Deque<Span>, Map<String, String>> linkTracingAndMdcToCurrentThread(
    Deque<Span> distributedTraceStackToLink, Map<String, String> mdcContextMapToLink
) {
    // Unregister the trace stack so that if there's already a trace on the stack we don't get exceptions when
    //      registering the desired stack with the thread, and keep a copy of the results.
    Map<String, String> callingThreadMdcContextMap = MDC.getCopyOfContextMap();
    Deque<Span> callingThreadTraceStack = Tracer.getInstance().unregisterFromThread();

    // Now setup the trace stack and MDC as desired
    if (mdcContextMapToLink == null)
        MDC.clear();
    else
        MDC.setContextMap(mdcContextMapToLink);

    Tracer.getInstance().registerWithThread(distributedTraceStackToLink);

    // Return the copied original data so that it can be re-linked later (if the caller wants)
    return Pair.of(callingThreadTraceStack, callingThreadMdcContextMap);
}
 
Example 19
Source File: ContextLogger.java    From EDDI with Apache License 2.0 4 votes vote down vote up
@Override
public void setLoggingContext(Map<String, String> loggingContext) {
    MDC.setContextMap(loggingContext);
}
 
Example 20
Source File: JettySolrRunner.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * Start the Jetty server
 *
 * @param reusePort when true, will start up on the same port as used by any
 *                  previous runs of this JettySolrRunner.  If false, will use
 *                  the port specified by the server's JettyConfig.
 *
 * @throws Exception if an error occurs on startup
 */
public void start(boolean reusePort) throws Exception {
  // Do not let Jetty/Solr pollute the MDC for this thread
  Map<String, String> prevContext = MDC.getCopyOfContextMap();
  MDC.clear();

  try {
    int port = reusePort && jettyPort != -1 ? jettyPort : this.config.port;
    log.info("Start Jetty (configured port={}, binding port={})", this.config.port, port);


    // if started before, make a new server
    if (startedBefore) {
      waitOnSolr = false;
      init(port);
    } else {
      startedBefore = true;
    }

    if (!server.isRunning()) {
      if (config.portRetryTime > 0) {
        retryOnPortBindFailure(config.portRetryTime, port);
      } else {
        server.start();
      }
    }
    synchronized (JettySolrRunner.this) {
      int cnt = 0;
      while (!waitOnSolr || !dispatchFilter.isRunning() || getCoreContainer() == null) {
        this.wait(100);
        if (cnt++ == 15) {
          throw new RuntimeException("Jetty/Solr unresponsive");
        }
      }
    }

    if (config.waitForLoadingCoresToFinishMs != null && config.waitForLoadingCoresToFinishMs > 0L) {
      waitForLoadingCoresToFinish(config.waitForLoadingCoresToFinishMs);
    }

    setProtocolAndHost();

    if (enableProxy) {
      if (started) {
        proxy.reopen();
      } else {
        proxy.open(getBaseUrl().toURI());
      }
    }

  } finally {
    started  = true;
    if (prevContext != null)  {
      MDC.setContextMap(prevContext);
    } else {
      MDC.clear();
    }
  }
}