Java Code Examples for org.apache.log4j.MDC#get()

The following examples show how to use org.apache.log4j.MDC#get() . 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: AgentManagerImpl.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private static void tagCommand(final Command cmd) {
    final AsyncJobExecutionContext context = AsyncJobExecutionContext.getCurrent();
    if (context != null && context.getJob() != null) {
        final AsyncJob job = context.getJob();

        if (job.getRelated() != null && !job.getRelated().isEmpty()) {
            cmd.setContextParam("job", "job-" + job.getRelated() + "/" + "job-" + job.getId());
        } else {
            cmd.setContextParam("job", "job-" + job.getId());
        }
    }
    String logcontextid = (String) MDC.get("logcontextid");
    if (!Strings.isNullOrEmpty(logcontextid)) {
        cmd.setContextParam("logid", logcontextid);
    }
}
 
Example 2
Source File: ReportErrorAction.java    From stendhal with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onAction(final Player player, final RPAction action) {
	if (!action.has(TEXT)) {
		return;
	}

	String username = PlayerEntryContainer.getContainer().get(player).username;

	// remove "context" because it contains a copy of the action with the error object.
	// Thus resulting a message with duplicated information that is hard to read
	Object context = MDC.get("context");
	MDC.remove("context");

	logger.error(player.getName() + " (" + username + "):"
	  + System.getProperty("line.separator")
	  + action.get(TEXT).replaceAll("\r\n", System.getProperty("line.separator")));

	MDC.put("context", context);
}
 
Example 3
Source File: CloverJMX.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public synchronized void setApprovedPhaseNumber(long runId, int approvedPhaseNumber, DictionaryValuesContainer mergedDictionary) {
	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, runId);
	try {
		
		WatchDog watchDog = getWatchDog(runId);
		setDictionary(watchDog, mergedDictionary);
		watchDog.setApprovedPhaseNumber(approvedPhaseNumber);
		
		notifyAll();
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 4
Source File: CloverJMX.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void releaseJob(long runId) {
	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, runId);
	try {
		WatchDog watchDog = watchDogCache.remove(runId);
		if (watchDog == null) {
			log.warn("Released WatchDog not found for runId #" + runId);
		} else {
			sendReleaseWatchdogNotification(watchDog);
			log.debug("WatchDog unregistered from CloverJMX #" + runId);
		}
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 5
Source File: CloverJMX.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public boolean abortGraphExecution(long runId, boolean waitForAbort) {
	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, runId);
	try {
		WatchDog watchDog = watchDogCache.get(runId);
		if (watchDog != null) {
			watchDog.abort(waitForAbort);
			return true;
		}
		return false;
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 6
Source File: Log4jLogEvent.java    From xian with Apache License 2.0 5 votes vote down vote up
@Override
public String getMdcValue(String mdcName) {
    Object value = MDC.get(mdcName);
    if (value != null) {
        return value.toString();
    }
    return null;
}
 
Example 7
Source File: MultipleFileAppender.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void append(LoggingEvent event) {
    Object value = MDC.get(FILE_NAMES);
    if (value != null) {
        Collection<String> names = (Collection<String>) value;
        for (String fileName : names) {
            append(fileName, event);
        }
    }
}
 
Example 8
Source File: FileAppender.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void append(LoggingEvent event) {
    Object value = MDC.get(FILE_NAME);
    if (value != null) {
        append(value.toString(), event);
    }
}
 
Example 9
Source File: LogAppender.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
public void doAppend(PaxLoggingEvent event) {
    try {
        if (MDC.get(MDC_IN_LOG_APPENDER) != null) {
            // Avoid recursion
            return;
        }
        MDC.put(MDC_IN_LOG_APPENDER, "true");
        appendInternal(event);
    } catch (Exception e) {
        LOGGER.warn("Error while appending event", e);
    } finally {
        MDC.remove(MDC_IN_LOG_APPENDER);
    }
}
 
Example 10
Source File: TrackingLogger.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void handleNotification(Notification notification, Object handback) {
	JMXNotificationMessage message = (JMXNotificationMessage) notification.getUserData();

	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, Long.valueOf(message.getRunId()));

	try {
		if(notification.getType().equals(CloverJMX.GRAPH_STARTED)) {
			graphStarted();
		} else if(notification.getType().equals(CloverJMX.TRACKING_UPDATED)) {
			trackingUpdated();
		} else if(notification.getType().equals(CloverJMX.PHASE_FINISHED)) {
			phaseFinished();
		} else if(notification.getType().equals(CloverJMX.PHASE_ABORTED)) {
			phaseAborted();
		} else if(notification.getType().equals(CloverJMX.PHASE_ERROR)) {
			phaseError();
		} else if(notification.getType().equals(CloverJMX.GRAPH_FINISHED)
				|| notification.getType().equals(CloverJMX.GRAPH_ABORTED)
				|| notification.getType().equals(CloverJMX.GRAPH_ERROR)) {
			graphFinished();
			try {
				CloverJMX.getInstance().removeNotificationListener(this);
			} catch (ListenerNotFoundException e) {
				logger.warn("Unexpected error while graph logging will be ignored.");
			}
		}
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 11
Source File: LogUtils.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Executes the Runnable with the MDC context set to <code>runId</code> and restores the original context afterwards.
 * 
 * @param runId		context job runId
 * @param runnable
 */
public static void runWithRunIdContext(long runId, Runnable runnable) {
	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, runId);
	try {
		runnable.run();
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 12
Source File: CloverJMX.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public GraphTracking getGraphTracking(long runId) {
	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, runId);
	try {
		return getWatchDog(runId).getGraphTracking();
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 13
Source File: MDCScopeDecorator.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public String getValue(String name) {
  Object result = MDC.get(name);
  return result instanceof String ? (String) result : null;
}
 
Example 14
Source File: WatchDog.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
@SuppressFBWarnings("NN_NAKED_NOTIFY")
public void abort(boolean waitForAbort) {
	final Object oldMDCRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	try {
		//update MDC for current thread to route logging message to correct logging destination 
		MDC.put(LogUtils.MDC_RUNID_KEY, runtimeContext.getRunId());

		currentPhaseLock.lock();
		if (watchDogStatus == Result.N_A || watchDogStatus == Result.READY) {
			waitForAbort = false;
		}
		//only running or waiting graph can be aborted
		if (watchDogStatus != Result.RUNNING && watchDogStatus != Result.WAITING) {
			//if the graph status is not final, so the graph was aborted
			if (!watchDogStatus.isStop()) {
		        watchDogStatus = Result.ABORTED;
			}
			return;
		}

		//if the phase is running broadcast all nodes in the phase they should be aborted
		if (watchDogStatus == Result.RUNNING) { 
	        watchDogStatus = Result.ABORTED;
			// iterate through all the nodes and stop them
	        for (Node node : currentPhase.getNodes().values()) {
				node.abort();
				logger.warn("Interrupted node: " + node.getId());
			}
		}
		//if the graph is waiting on a phase synchronization point the watchdog is woken up with current status ABORTED 
		if (watchDogStatus == Result.WAITING) {
	        watchDogStatus = Result.ABORTED;
			synchronized (CloverJMX.getInstance()) {
				CloverJMX.getInstance().notifyAll();
			}
		}
	} catch (RuntimeException e) {
		throw new JetelRuntimeException("Graph abort failed.", e);
	} finally {
		try {
			synchronized (abortMonitor) {
				currentPhaseLock.unlock();
				if (waitForAbort) {
					long startAbort = System.currentTimeMillis();
					while (!abortFinished) {
						long interval = System.currentTimeMillis() - startAbort;
						if (interval > ABORT_TIMEOUT) {
							throw new IllegalStateException(String.format("Graph %d aborting error! Timeout %dms exceeded!", graphTracking.getRunId(), ABORT_TIMEOUT));
						}
				        try {
				        	//the aborting thread try to wait for end of graph run
							abortMonitor.wait(ABORT_WAIT);
						} catch (InterruptedException ignore) {	}// catch
					}// while
				}
			}// synchronized
		} finally {
			//rollback MDC
			MDC.remove(LogUtils.MDC_RUNID_KEY);
			if (oldMDCRunId != null) {
				MDC.put(LogUtils.MDC_RUNID_KEY, oldMDCRunId);
			}
		}
	}// finally
}
 
Example 15
Source File: Log4jAuditService.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public AuditContext detachContext() {
  AuditContext context = (AuditContext) MDC.get( MDC_AUDIT_CONTEXT_KEY );
  MDC.remove( MDC_AUDIT_CONTEXT_KEY );
  return context;
}
 
Example 16
Source File: Log4jCorrelationService.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public CorrelationContext detachContext() {
  CorrelationContext context = (CorrelationContext) MDC.get( MDC_CORRELATION_CONTEXT_KEY );
  MDC.remove( MDC_CORRELATION_CONTEXT_KEY );
  return context;
}
 
Example 17
Source File: Log4jCorrelationService.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public CorrelationContext getContext() {
  return (CorrelationContext) MDC.get( MDC_CORRELATION_CONTEXT_KEY );
}
 
Example 18
Source File: TraceContextConfig.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@Override
public Scope newScope(TraceContext currentSpan) {
  final Object previousTraceId = MDC.get("traceId");
  final Object previousSpanId = MDC.get("spanId");
  final Object previousParentId = MDC.get("parentId");

  if (currentSpan != null) {
    MDC.put("traceId", currentSpan.traceIdString());
    MDC.put("spanId", HexCodec.toLowerHex(currentSpan.spanId()));
    if (currentSpan.parentId() != null) {
      MDC.put("parentId", HexCodec.toLowerHex(currentSpan.parentId()));
    }
  } else {
    MDC.remove("traceId");
    MDC.remove("spanId");
    MDC.remove("parentId");
  }

  Scope scope = delegate.newScope(currentSpan);
  class MDCCurrentTraceContextScope implements Scope {
    @Override
    public void close() {
      scope.close();
      if (previousTraceId != null) {
        MDC.put("traceId", previousTraceId);
      } else {
        MDC.remove("traceId");
      }

      if (previousSpanId != null) {
        MDC.put("spanId", previousSpanId);
      } else {
        MDC.remove("spanId");
      }

      if (previousParentId != null) {
        MDC.put("parentId", previousParentId);
      } else {
        MDC.remove("parentId");
      }
    }
  }
  return new MDCCurrentTraceContextScope();
}
 
Example 19
Source File: Log4j1MsgIdHolder.java    From xian with Apache License 2.0 4 votes vote down vote up
@Override
protected String get0() {
    return MDC.get(MSG_ID_KEY) == null ? null : MDC.get(MSG_ID_KEY).toString();
}
 
Example 20
Source File: Util.java    From identity-api-server with Apache License 2.0 2 votes vote down vote up
/**
 * Check whether correlation id present in the log MDC
 *
 * @return whether the correlation id is present
 */
public static boolean isCorrelationIDPresent() {
    return MDC.get(Constants.CORRELATION_ID_MDC) != null;
}