Java Code Examples for org.apache.log4j.NDC#push()
The following examples show how to use
org.apache.log4j.NDC#push() .
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: Log4JController.java From tutorials with MIT License | 6 votes |
@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); }
Example 2
Source File: SocketServerTestCase.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * 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")); } }
Example 3
Source File: XMLLayoutTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * 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()); }
Example 4
Source File: MessageLogFilter.java From unitime with Apache License 2.0 | 6 votes |
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; }
Example 5
Source File: ImhotepDaemon.java From imhotep with Apache License 2.0 | 6 votes |
@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; } }
Example 6
Source File: Log4jNestedDiagnosticContextFilter.java From lams with GNU General Public License v2.0 | 5 votes |
/** * 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)); }
Example 7
Source File: SocketServer2.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
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"); }
Example 8
Source File: Trivial.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
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."); }
Example 9
Source File: InitUsingDefaultConfigurator.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
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."); }
Example 10
Source File: InitUsingDefaultConfigurator.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
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(); }
Example 11
Source File: SocketServerTestCase.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * 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")); } }
Example 12
Source File: HighAvailabilityManagerImpl.java From cloudstack with Apache License 2.0 | 5 votes |
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(); } } }
Example 13
Source File: Log4jNestedDiagnosticContextInterceptor.java From spring4-understanding with Apache License 2.0 | 4 votes |
/** * Adds a message the Log4J NDC before the request is processed. */ @Override public void preHandle(WebRequest request) throws Exception { NDC.push(getNestedDiagnosticContextMessage(request)); }
Example 14
Source File: VmwareSecondaryStorageResourceHandler.java From cloudstack with Apache License 2.0 | 4 votes |
@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(); } }
Example 15
Source File: Log4jEcsLayoutTest.java From ecs-logging-java with Apache License 2.0 | 4 votes |
@Override public boolean putNdc(String message) { NDC.push(message); return true; }
Example 16
Source File: NumberCruncherServer.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
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; }
Example 17
Source File: FlowIdUtils.java From nakadi with MIT License | 4 votes |
public static void push(final String flowId) { NDC.push(flowId); }
Example 18
Source File: XMLLayoutTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
/** * 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; } } }
Example 19
Source File: AtlasAuthenticationFilter.java From atlas with Apache License 2.0 | 4 votes |
@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(); } } }
Example 20
Source File: NDCUtils.java From seezoon-framework-all with Apache License 2.0 | 4 votes |
public static void push() { clear(); NDC.push(randomThreadId()); }