org.apache.log4j.NDC#push ( )源码实例Demo

下面列出了org.apache.log4j.NDC#push ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: tutorials   文件: Log4JController.java
@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);
}
 
源代码2 项目: imhotep   文件: ImhotepDaemon.java
@Override
public void run() {
    try {
        final InetAddress remoteAddress = socket.getInetAddress();
        NDC.push("DaemonWorker(" + socket.getRemoteSocketAddress() + ")");
        try {
            internalRun();
        } finally {
            NDC.pop();
        }
    } catch (RuntimeException e) {
        if (e.getCause() instanceof SocketException) {
            log.warn("worker exception", e);
        } else if (e instanceof IllegalArgumentException) {
            log.warn("worker exception", e);
        } else {
            log.error("worker exception", e);
        }
        throw e;
    }
}
 
源代码3 项目: unitime   文件: MessageLogFilter.java
private int ndcPush() {
	int count = 0;
	try {
		UserContext user = getUser();
		if (user != null) {
			NDC.push("uid:" + user.getTrueExternalUserId()); count++;
			if (user.getCurrentAuthority() != null) {
				NDC.push("role:" + user.getCurrentAuthority().getRole()); count++;
				Long sessionId = user.getCurrentAcademicSessionId();
				if (sessionId != null) {
					NDC.push("sid:" + sessionId); count++;
				}
			}
		}
	} catch (Exception e) {}
	return count;
}
 
源代码4 项目: cacheonix-core   文件: XMLLayoutTest.java
/**
   * Tests CDATA element within NDC content.  See bug 37560.
   */
 public void testNDCWithCDATA() throws Exception {
     Logger logger = Logger.getLogger("com.example.bar");
     Level level = Level.INFO;
     String ndcMessage ="<envelope><faultstring><![CDATA[The EffectiveDate]]></faultstring><envelope>";
     NDC.push(ndcMessage);
     LoggingEvent event =
       new LoggingEvent(
         "com.example.bar", logger, level, "Hello, World", null);
     Layout layout = createLayout();
     String result = layout.format(event);
     NDC.clear();
     Element parsedResult = parse(result);
     NodeList ndcs = parsedResult.getElementsByTagName("log4j:NDC");
     assertEquals(1, ndcs.getLength());
     StringBuffer buf = new StringBuffer();
     for(Node child = ndcs.item(0).getFirstChild();
             child != null;
             child = child.getNextSibling()) {
         buf.append(child.getNodeValue());
     }
     assertEquals(ndcMessage, buf.toString());
}
 
源代码5 项目: cacheonix-core   文件: SocketServerTestCase.java
/**
 *  The pattern on the server side: %5p %x %X{key1}%X{key4} [%t] %c{1} - %m%n 
 *  meaning that we are testing NDC, MDC and localization functionality across 
 *  the wire.  
*/
public void test4() throws Exception {
  socketAppender = new SocketAppender("localhost", PORT);
  socketAppender.setLocationInfo(true);
  rootLogger.addAppender(socketAppender);

  NDC.push("some");
  common("T4", "key4", "MDC-TEST4");
  NDC.pop();
  delay(1);
  //
  //  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[]{PAT4, EXCEPTION1, 
				           EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
      Transformer.transform(
        TEMP, FILTERED,
        new Filter[] { cf, new LineNumberFilter(), 
            new JunitTestRunnerFilter(),
            new SunReflectFilter() });

      assertTrue(Compare.compare(FILTERED, "witness/socketServer.4"));
  }
}
 
源代码6 项目: cloudstack   文件: HighAvailabilityManagerImpl.java
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();
        }
    }
}
 
源代码7 项目: lams   文件: Log4jNestedDiagnosticContextFilter.java
/**
 * Logs the before-request message through Log4J and
 * adds a message the Log4J NDC before the request is processed.
 */
@Override
protected void beforeRequest(HttpServletRequest request, String message) {
	if (log4jLogger.isDebugEnabled()) {
		log4jLogger.debug(message);
	}
	NDC.push(getNestedDiagnosticContextMessage(request));
}
 
源代码8 项目: cacheonix-core   文件: SocketServer2.java
static
 void init(String portStr, String configFile) {
try {
  port   = Integer.parseInt(portStr);
}
catch(java.lang.NumberFormatException e) {
  e.printStackTrace();
  usage("Could not interpret port number ["+ portStr +"].");
}
PropertyConfigurator.configure(configFile);
NDC.push("Server");
 }
 
源代码9 项目: cacheonix-core   文件: Trivial.java
public static void main(String[] args) {
  BasicConfigurator.configure();
  NDC.push("Client #45890"); 

  logger.info("Awake awake. Put on thy strength.");
  Trivial.foo();
  InnerTrivial.foo();
  logger.info("Exiting Trivial.");    
}
 
public static void main(String[] args) throws IOException {
    // Configure the LF5Appender using the DefaultLF5Configurator.  This
    // will add the LF5Appender to the root of the Category tree.
    DefaultLF5Configurator.configure();

    // Add an NDC to demonstrate how NDC information is output.
    NDC.push("#23856");
    // Log some information.
    for (int i = 0; i < 10; i++) {
        logger.debug("Hello, my name is Homer Simpson.");
        logger.info("Mmmmmm .... Chocolate.");
        logger.warn("Mmm...forbidden donut.");
    }
    // Clean up NDC
    NDC.pop();
    NDC.remove();

    NDC.push("Another NDC");
    // Log some information.
    logger.fatal("Hello, my name is Bart Simpson.");
    logger.error("Hi diddly ho good neighbour.");
    // Clean up NDC
    NDC.pop();
    NDC.remove();

    // Call methods on both classes.
    InitUsingDefaultConfigurator.foo();
    InnerInitUsingDefaultConfigurator.foo();

    logger.info("Exiting InitUsingDefaultConfigurator.");

}
 
public static void foo() {
    logger.debug("Entered foo in InitUsingDefaultConfigurator class");

    NDC.push("#123456");
    logger.debug("Hello, my name is Marge Simpson.");
    logger.info("D'oh!! A deer! A female deer.");
    // Clean up NDC
    NDC.pop();
    NDC.remove();
}
 
源代码12 项目: cacheonix-core   文件: SocketServerTestCase.java
/**
 * The pattern on the server side: %5p %x %X{hostID}${key6} [%t] %c{1} - %m%n 
 *
 * This test checks whether client-side MDC overrides the server side.
 * It uses an AsyncAppender encapsulating a SocketAppender
 */
public void test6() 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("some6");
  MDC.put("hostID", "client-test6");
  common("T6", "key6", "MDC-TEST6");
  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[]{PAT6, EXCEPTION1, 
				           EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
  
      Transformer.transform(
        TEMP, FILTERED,
        new Filter[] { cf, new LineNumberFilter(), 
            new JunitTestRunnerFilter(),
            new SunReflectFilter() });

      assertTrue(Compare.compare(FILTERED, "witness/socketServer.6"));
  }
}
 
源代码13 项目: ecs-logging-java   文件: Log4jEcsLayoutTest.java
@Override
public boolean putNdc(String message) {
    NDC.push(message);
    return true;
}
 
源代码14 项目: seezoon-framework-all   文件: NDCUtils.java
public static void push() {
	clear();
	NDC.push(randomThreadId());
}
 
源代码15 项目: atlas   文件: AtlasAuthenticationFilter.java
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
    final HttpServletRequest  httpRequest  = (HttpServletRequest) servletRequest;
    final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    final Authentication      existingAuth = SecurityContextHolder.getContext().getAuthentication();
    String                    loggedInUser = readUserFromCookie(httpResponse);
    String                    userName     = loggedInUser;

    if (!StringUtils.isEmpty((String) httpRequest.getAttribute("proxyUser"))) {
        userName = (String) httpRequest.getAttribute("proxyUser");
    } else if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(httpRequest.getRemoteUser())) {
        userName = httpRequest.getRemoteUser();
    }

    if ((existingAuth == null || !existingAuth.isAuthenticated()) && !StringUtils.isEmpty(userName)) {
        final List<GrantedAuthority>   grantedAuths        = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
        final UserDetails              principal           = new User(userName, "", grantedAuths);
        final Authentication           finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
        final WebAuthenticationDetails webDetails          = new WebAuthenticationDetails(httpRequest);

        ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);

        SecurityContextHolder.getContext().setAuthentication(finalAuthentication);

        request.setAttribute("atlas.http.authentication.type", true);

        if (!StringUtils.equals(loggedInUser, userName)) {
            LOG.info("Logged into Atlas as = {}, by proxyUser = {}", userName, loggedInUser);
        } else {
            LOG.info("Logged into Atlas as = {}", userName);
        }
    }

    // OPTIONS method is sent from quick start jersey atlas client
    if (httpRequest.getMethod().equals("OPTIONS")) {
        optionsServlet.service(request, response);
    } else {
        try {
            String requestUser = httpRequest.getRemoteUser();

            NDC.push(requestUser + ":" + httpRequest.getMethod() + httpRequest.getRequestURI());

            LOG.info("Request from authenticated user: {}, URL={}", requestUser, Servlets.getRequestURI(httpRequest));

            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            NDC.pop();
        }
    }
}
 
源代码16 项目: nakadi   文件: FlowIdUtils.java
public static void push(final String flowId) {
    NDC.push(flowId);
}
 
/**
 * Adds a message the Log4J NDC before the request is processed.
 */
@Override
public void preHandle(WebRequest request) throws Exception {
	NDC.push(getNestedDiagnosticContextMessage(request));
}
 
@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();
    }
}
 
源代码19 项目: cacheonix-core   文件: NumberCruncherServer.java
public
 int[] factor(int number) throws RemoteException {

   // The client's host is an important source of information.
   try {
     NDC.push(getClientHost());
   }
   catch(java.rmi.server.ServerNotActiveException e) {
     // we are being called from same VM
     NDC.push("localhost");
   }

   // The information contained within the request is another source of
   // distinctive information. It might reveal the users name, date of request,
   // request ID etc. In servlet type environments, much information is
   // contained in cookies.
   NDC.push(String.valueOf(number));    

   logger.info("Beginning to factor.");
   if(number <= 0) {
     throw new IllegalArgumentException(number+" is not a positive integer.");
   }
   else if(number == 1)
      return new int[] {1};
   
   Vector factors = new Vector();
   int n = number;

   for(int i = 2; (i <= n) && (i*i <= number); i++) {
     // It is bad practice to place log requests within tight loops.
     // It is done here to show interleaved log output from
     // different requests. 
     logger.debug("Trying to see if " + i + " is a factor.");

     if((n % i) == 0) {
logger.info("Found factor "+i);
factors.addElement(new Integer(i));
do {
  n /= i;
} while((n % i) == 0);
     }
     // Placing artificial delays in tight-loops will also lead to sub-optimal
     // resuts. :-)
     delay(100);
   }

   if(n != 1) {
     logger.info("Found factor "+n);
     factors.addElement(new Integer(n));
   }
   
   int len = factors.size();
   
   int[] result = new int[len];
   for(int i = 0; i < len; i++) {
     result[i] = ((Integer) factors.elementAt(i)).intValue();
   }

   // Before leaving a thread we call NDC.remove. This deletes the reference
   // to the thread in the internal hash table. Version 0.8.5 introduces a
   // a lazy removal mechanism in case you forget to call remove when
   // exiting a thread. See the java documentation in NDC.remove for further
   // details.
   NDC.remove();
   
   return result;
 }
 
源代码20 项目: cacheonix-core   文件: XMLLayoutTest.java
/**
 * Tests problematic characters in multiple fields.
 * @throws Exception if parser can not be constructed or source is not a valid XML document.
 */
public void testProblemCharacters() throws Exception {
  String problemName = "com.example.bar<>&\"'";
  Logger logger = Logger.getLogger(problemName);
  Level level = new ProblemLevel(problemName);
  Exception ex = new IllegalArgumentException(problemName);
  String threadName = Thread.currentThread().getName();
  Thread.currentThread().setName(problemName);
  NDC.push(problemName);
  Hashtable mdcMap = MDC.getContext();
  if (mdcMap != null) {
      mdcMap.clear();
  }
  MDC.put(problemName, problemName);
  LoggingEvent event =
    new LoggingEvent(
      problemName, logger, level, problemName, ex);
  XMLLayout layout = (XMLLayout) createLayout();
  layout.setProperties(true);
  String result = layout.format(event);
  mdcMap = MDC.getContext();
  if (mdcMap != null) {
      mdcMap.clear();
  }
  Thread.currentThread().setName(threadName);

  Element parsedResult = parse(result);
  checkEventElement(parsedResult, event);

  int childElementCount = 0;

  for (
    Node node = parsedResult.getFirstChild(); node != null;
      node = node.getNextSibling()) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      childElementCount++;
      switch(childElementCount) {
          case 1:
          checkMessageElement((Element) node, problemName);
          break;

          case 2:
          checkNDCElement((Element) node, problemName);
          break;

          case 3:
          checkThrowableElement((Element) node, ex);
          break;

          case 4:
          checkPropertiesElement((Element) node, problemName, problemName);
          break;

          default:
          fail("Unexpected element");
          break;
      }

      break;

    case Node.COMMENT_NODE:
      break;

    case Node.TEXT_NODE:

      //  should only be whitespace
      break;

    default:
      fail("Unexpected node type");

      break;
    }
  }
}