下面列出了org.slf4j.MDC#setContextMap ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
}
@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);
}
}
}
@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);
}
}
}
@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);
}
}
}
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);
}
}
/**
* 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);
}
@Override
public T call() throws Exception {
try {
threadLocalState.propagate();
if (currentMdcState != null) {
MDC.setContextMap(currentMdcState);
}
return wrapped.call();
} finally {
threadLocalState.cleanup();
MDC.clear();
}
}
@Override
public V call() throws Exception {
try(MdcContextReference ref = MdcContext.captureMdcContext()) {
MDC.setContextMap(mdc);
return delegate.call();
}
}
/**
* 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();
}
}
}
@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
}
@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;
}
}
@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;
}
@Override
public T call() throws Exception {
try {
MDC.setContextMap(contextMap);
return callable.call();
} finally {
MDC.clear();
}
}
/**
* 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);
}
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);
}
}
}
@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);
}
}
@Override
public void run() {
try {
threadLocalState.propagate();
if (currentMdcState != null) {
MDC.setContextMap(currentMdcState);
}
wrapped.run();
} finally {
threadLocalState.cleanup();
MDC.clear();
}
}
/**
* 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);
}
@Override
public void setLoggingContext(Map<String, String> loggingContext) {
MDC.setContextMap(loggingContext);
}
/**
* 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();
}
}
}