下面列出了org.apache.log4j.NDC#pop ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequestMapping(value = "/ndc/log4j", method = RequestMethod.POST)
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
// Add transactionId and owner to NDC
NDC.push("tx.id=" + investment.getTransactionId());
NDC.push("tx.owner=" + investment.getOwner());
try {
log4jBusinessService.transfer(investment.getAmount());
} finally {
// take out owner from the NDC stack
NDC.pop();
// take out transactionId from the NDC stack
NDC.pop();
NDC.remove();
}
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
}
void bubbleSort() {
LOG.info( "Entered the sort method.");
for(int i = intArray.length -1; i >= 0 ; i--) {
NDC.push("i=" + i);
OUTER.debug("in outer loop.");
for(int j = 0; j < i; j++) {
NDC.push("j=" + j);
// It is poor practice to ship code with log staments in tight loops.
// We do it anyway in this example.
INNER.debug( "in inner loop.");
if(intArray[j] > intArray[j+1])
swap(j, j+1);
NDC.pop();
}
NDC.pop();
}
}
/**
* The pattern on the server side: %5p %x %X{hostID}${key7} [%t] %c{1} - %m%n
*
* This test checks whether server side MDC works.
*/
public void test8() throws Exception {
socketAppender = new SocketAppender("localhost", PORT);
socketAppender.setLocationInfo(true);
rootLogger.addAppender(socketAppender);
NDC.push("some8");
common("T8", "key8", "MDC-TEST8");
NDC.pop();
delay(2);
//
// These tests check MDC operation which
// requires JDK 1.2 or later
if(!System.getProperty("java.version").startsWith("1.1.")) {
ControlFilter cf = new ControlFilter(new String[]{PAT8, EXCEPTION1,
EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
Transformer.transform(
TEMP, FILTERED,
new Filter[] { cf, new LineNumberFilter(),
new JunitTestRunnerFilter(),
new SunReflectFilter() });
assertTrue(Compare.compare(FILTERED, "witness/socketServer.8"));
}
}
public void run() {
NDC.push("main");
try {
log.info("starting up daemon");
isStarted = true;
//noinspection InfiniteLoopStatement
while (!ss.isClosed()) {
try {
final Socket socket = ss.accept();
socket.setSoTimeout(60000);
socket.setTcpNoDelay(true);
log.info("received connection, running");
executor.execute(new DaemonWorker(socket));
} catch (IOException e) {
log.warn("server socket error", e);
}
}
} finally {
NDC.pop();
}
}
/**
* Removes the log message from the Log4J NDC after the request is processed.
*/
@Override
public void afterCompletion(WebRequest request, Exception ex) throws Exception {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
}
/**
* Removes the log message from the Log4J NDC when the processing thread is
* exited after the start of asynchronous request handling.
*/
@Override
public void afterConcurrentHandlingStarted(WebRequest request) {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
}
/**
* Removes the log message from the Log4J NDC after the request is processed
* and logs the after-request message through Log4J.
*/
@Override
protected void afterRequest(HttpServletRequest request, String message) {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
if (log4jLogger.isDebugEnabled()) {
log4jLogger.debug(message);
}
}
@Override
public List<Host> allocateTo(VirtualMachineProfile vmProfile, DeploymentPlan plan, Type type, ExcludeList avoid, int returnUpTo) {
try {
NDC.push("FirstFitRoutingAllocator");
if (type != Host.Type.Routing) {
// FirstFitRoutingAllocator is to find space on routing capable hosts only
return new ArrayList<Host>();
}
//all hosts should be of type routing anyway.
return super.allocateTo(vmProfile, plan, type, avoid, returnUpTo);
} finally {
NDC.pop();
}
}
/**
* Removes the log message from the Log4J NDC when the processing thread is
* exited after the start of asynchronous request handling.
*/
@Override
public void afterConcurrentHandlingStarted(WebRequest request) {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
}
/**
* Removes the log message from the Log4J NDC after the request is processed
* and logs the after-request message through Log4J.
*/
@Override
protected void afterRequest(HttpServletRequest request, String message) {
NDC.pop();
if (NDC.getDepth() == 0) {
NDC.remove();
}
if (log4jLogger.isDebugEnabled()) {
log4jLogger.debug(message);
}
}
private void runWithContext() {
HaWorkVO work = null;
try {
s_logger.trace("Checking the database for work");
work = _haDao.take(_serverId);
if (work == null) {
try {
synchronized (this) {
wait(_timeToSleep);
}
return;
} catch (final InterruptedException e) {
s_logger.info("Interrupted");
return;
}
}
NDC.push("work-" + work.getId());
s_logger.info("Processing work " + work);
processWork(work);
} catch (final Throwable th) {
s_logger.error("Caught this throwable, ", th);
} finally {
if (work != null) {
NDC.pop();
}
}
}
/**
* Remove the appender and context from the NDC
*/
private void resetNDCLogging() {
if ( ndcSet ) {
ndcAppender.close();
Logger.getRootLogger().removeAppender(ndcAppender);
NDC.pop();
}
}
/**
* The pattern on the server side: %5p %x %X{key1}%X{key5} [%t] %c{1} - %m%n
*
* The test case uses wraps an AsyncAppender around the
* SocketAppender. This tests was written specifically for bug
* report #9155.
* Prior to the bug fix the output on the server did not contain the
* MDC-TEST5 string because the MDC clone operation (in getMDCCopy
* method) operation is performed twice, once from the main thread
* which is correct, and a second time from the AsyncAppender's
* dispatch thread which is incrorrect.
*/
public void test5() throws Exception {
socketAppender = new SocketAppender("localhost", PORT);
socketAppender.setLocationInfo(true);
AsyncAppender asyncAppender = new AsyncAppender();
asyncAppender.setLocationInfo(true);
asyncAppender.addAppender(socketAppender);
rootLogger.addAppender(asyncAppender);
NDC.push("some5");
common("T5", "key5", "MDC-TEST5");
NDC.pop();
delay(2);
//
// These tests check MDC operation which
// requires JDK 1.2 or later
if(!System.getProperty("java.version").startsWith("1.1.")) {
ControlFilter cf = new ControlFilter(new String[]{PAT5, EXCEPTION1,
EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
Transformer.transform(
TEMP, FILTERED,
new Filter[] { cf, new LineNumberFilter(),
new JunitTestRunnerFilter(),
new SunReflectFilter() });
assertTrue(Compare.compare(FILTERED, "witness/socketServer.5"));
}
}
public static CallContext unregister() {
CallContext context = s_currentContext.get();
if (context == null) {
return null;
}
s_currentContext.remove();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Unregistered: " + context);
}
String contextId = context.getContextId();
String sessionIdOnStack = null;
String sessionIdPushedToNDC = "ctx-" + UuidUtils.first(contextId);
while ((sessionIdOnStack = NDC.pop()) != null) {
if (sessionIdOnStack.isEmpty() || sessionIdPushedToNDC.equals(sessionIdOnStack)) {
break;
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Popping from NDC: " + contextId);
}
}
Stack<CallContext> stack = s_currentContextStack.get();
stack.pop();
if (!stack.isEmpty()) {
s_currentContext.set(stack.peek());
} else {
s_currentContext.set(null);
}
return context;
}
/**
* The pattern on the server side: %5p %x %X{hostID}${key7} [%t] %c{1} - %m%n
*
* This test checks whether client-side MDC overrides the server side.
*/
public void test7() throws Exception {
socketAppender = new SocketAppender("localhost", PORT);
socketAppender.setLocationInfo(true);
rootLogger.addAppender(socketAppender);
NDC.push("some7");
MDC.put("hostID", "client-test7");
common("T7", "key7", "MDC-TEST7");
NDC.pop();
MDC.remove("hostID");
delay(2);
//
// These tests check MDC operation which
// requires JDK 1.2 or later
if(!System.getProperty("java.version").startsWith("1.1.")) {
ControlFilter cf = new ControlFilter(new String[]{PAT7, EXCEPTION1,
EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
Transformer.transform(
TEMP, FILTERED,
new Filter[] { cf, new LineNumberFilter(),
new JunitTestRunnerFilter(),
new SunReflectFilter() });
assertTrue(Compare.compare(FILTERED, "witness/socketServer.7"));
}
}
static
void common(String dc, String key, Object o) {
String oldThreadName = Thread.currentThread().getName();
Thread.currentThread().setName("main");
int i = -1;
NDC.push(dc);
MDC.put(key, o);
Logger root = Logger.getRootLogger();
logger.setLevel(Level.DEBUG);
rootLogger.setLevel(Level.DEBUG);
logger.log(XLevel.TRACE, "Message " + ++i);
logger.setLevel(Level.TRACE);
rootLogger.setLevel(Level.TRACE);
logger.trace("Message " + ++i);
root.trace("Message " + ++i);
logger.debug("Message " + ++i);
root.debug("Message " + ++i);
logger.info("Message " + ++i);
logger.warn("Message " + ++i);
logger.log(XLevel.LETHAL, "Message " + ++i); //5
Exception e = new Exception("Just testing");
logger.debug("Message " + ++i, e);
root.error("Message " + ++i, e);
NDC.pop();
MDC.remove(key);
Thread.currentThread().setName(oldThreadName);
}
public static String pop() {
return NDC.pop();
}
static
void foo() {
NDC.push("DB");
logger.debug("Now king David was old.");
NDC.pop();
}
@Override
public Answer executeRequest(Command cmd) {
try {
Answer answer;
NDC.push(getCommandLogTitle(cmd));
if (s_logger.isDebugEnabled())
s_logger.debug("Executing " + _gson.toJson(cmd));
if (cmd instanceof PrimaryStorageDownloadCommand) {
answer = execute((PrimaryStorageDownloadCommand)cmd);
} else if (cmd instanceof BackupSnapshotCommand) {
answer = execute((BackupSnapshotCommand)cmd);
} else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
answer = execute((CreatePrivateTemplateFromVolumeCommand)cmd);
} else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
answer = execute((CreatePrivateTemplateFromSnapshotCommand)cmd);
} else if (cmd instanceof CopyVolumeCommand) {
answer = execute((CopyVolumeCommand)cmd);
} else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
answer = execute((CreateVolumeFromSnapshotCommand)cmd);
} else if (cmd instanceof StorageSubSystemCommand) {
answer = storageSubsystemHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
} else if (cmd instanceof CreateEntityDownloadURLCommand) {
answer = execute((CreateEntityDownloadURLCommand)cmd);
} else {
answer = _resource.defaultAction(cmd);
}
// special handling to pass-back context info for cleanups
if (cmd.getContextParam("execid") != null) {
answer.setContextParam("execid", cmd.getContextParam("execid"));
}
if (cmd.getContextParam("checkpoint") != null) {
answer.setContextParam("checkpoint", cmd.getContextParam("checkpoint"));
}
if (cmd.getContextParam("checkpoint2") != null) {
answer.setContextParam("checkpoint2", cmd.getContextParam("checkpoint2"));
}
if (s_logger.isDebugEnabled())
s_logger.debug("Command execution answer: " + _gson.toJson(answer));
return answer;
} finally {
if (s_logger.isDebugEnabled())
s_logger.debug("Done executing " + _gson.toJson(cmd));
recycleServiceContext();
NDC.pop();
}
}
private void ndcPop(int count) {
for (int i = 0; i < count; i++)
NDC.pop();
}