org.apache.log4j.NDC Java Examples
The following examples show how to use
org.apache.log4j.NDC.
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: ImhotepDaemon.java From imhotep with Apache License 2.0 | 6 votes |
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(); } }
Example #2
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 #3
Source File: CallContext.java From cloudstack with Apache License 2.0 | 6 votes |
protected static CallContext register(User callingUser, Account callingAccount, Long userId, Long accountId, String contextId) { /* Unit tests will have multiple times of setup/tear-down call to this, remove assertions to all unit test to run assert s_currentContext.get() == null : "There's a context already so what does this new register context mean? " + s_currentContext.get().toString(); if (s_currentContext.get() != null) { // FIXME: This should be removed soon. I added this check only to surface all the places that have this problem. throw new CloudRuntimeException("There's a context already so what does this new register context mean? " + s_currentContext.get().toString()); } */ CallContext callingContext = null; if (userId == null || accountId == null) { callingContext = new CallContext(callingUser, callingAccount, contextId); } else { callingContext = new CallContext(userId, accountId, contextId); } s_currentContext.set(callingContext); NDC.push("ctx-" + UuidUtils.first(contextId)); if (s_logger.isTraceEnabled()) { s_logger.trace("Registered: " + callingContext); } s_currentContextStack.get().push(callingContext); return callingContext; }
Example #4
Source File: SortAlgo.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
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(); } }
Example #5
Source File: JobListener.java From kfs with GNU Affero General Public License v3.0 | 6 votes |
protected void notify(JobExecutionContext jobExecutionContext, String jobStatus) { try { StringBuilder mailMessageSubject = new StringBuilder(jobExecutionContext.getJobDetail().getGroup()).append(": ").append(jobExecutionContext.getJobDetail().getName()); MailMessage mailMessage = new MailMessage(); mailMessage.setFromAddress(mailService.getBatchMailingList()); if (jobExecutionContext.getMergedJobDataMap().containsKey(REQUESTOR_EMAIL_ADDRESS_KEY) && !StringUtils.isBlank(jobExecutionContext.getMergedJobDataMap().getString(REQUESTOR_EMAIL_ADDRESS_KEY))) { mailMessage.addToAddress(jobExecutionContext.getMergedJobDataMap().getString(REQUESTOR_EMAIL_ADDRESS_KEY)); } if (SchedulerService.FAILED_JOB_STATUS_CODE.equals(jobStatus) || SchedulerService.CANCELLED_JOB_STATUS_CODE.equals(jobStatus)) { mailMessage.addToAddress(mailService.getBatchMailingList()); } mailMessageSubject.append(": ").append(jobStatus); String messageText = MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.MESSAGE_BATCH_FILE_LOG_EMAIL_BODY), getLogFileName(NDC.peek())); mailMessage.setMessage(messageText); if (mailMessage.getToAddresses().size() > 0) { mailMessage.setSubject(mailMessageSubject.toString()); mailService.sendMessage(mailMessage); } } catch (Exception iae) { LOG.error("Caught exception while trying to send job completion notification e-mail for " + jobExecutionContext.getJobDetail().getName(), iae); } }
Example #6
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 #7
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 #8
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{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")); } }
Example #9
Source File: HttpServletSupport.java From openid4java with Apache License 2.0 | 6 votes |
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { count_++; String ndcName = getClass().getName(); ndcName = ndcName.substring(ndcName.lastIndexOf('.')+1); NDC.push(ndcName); NDC.push("call-" + count_); logger_.info("begin onService"); try { onService(req, resp); } catch (Exception exc) { lastException = exc; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { logger_.info("end onService"); NDC.pop(); NDC.pop(); } }
Example #10
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 #11
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 #12
Source File: Log4jNestedDiagnosticContextInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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(); } }
Example #13
Source File: Log4jNestedDiagnosticContextInterceptor.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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(); } }
Example #14
Source File: Log4jNestedDiagnosticContextFilter.java From spring4-understanding with Apache License 2.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 #15
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 #16
Source File: LoggingEventTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Serialize a logging event with ndc. * @throws Exception if exception during test. * */ public void testSerializationNDC() throws Exception { Logger root = Logger.getRootLogger(); NDC.push("ndc test"); LoggingEvent event = new LoggingEvent( root.getClass().getName(), root, Level.INFO, "Hello, world.", null); // event.prepareForDeferredProcessing(); int[] skip = new int[] { 352, 353, 354, 355, 356 }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/ndc.bin", event, skip, 237); }
Example #17
Source File: XMLLayoutTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Clear MDC and NDC before test. */ public void setUp() { NDC.clear(); if (MDC.getContext() != null) { MDC.getContext().clear(); } }
Example #18
Source File: Log4JContextClearingFilter.java From rice with Educational Community License v2.0 | 5 votes |
/** * Clear Log4J threadlocals */ protected static void clearLog4JThreadLocals() { NDC.remove(); MDC.clear(); ThreadLocal tl = getMDCThreadLocal(); if (tl != null) { tl.remove(); } }
Example #19
Source File: Log4jNestedDiagnosticContextFilter.java From lams with GNU General Public License v2.0 | 5 votes |
/** * 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); } }
Example #20
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{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")); } }
Example #21
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 #22
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}${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")); } }
Example #23
Source File: CallableWithNdc.java From tez with Apache License 2.0 | 5 votes |
@Override public final T call() throws Exception { NDC.inherit(ndcStack); try { return callInternal(); } finally { NDC.clear(); } }
Example #24
Source File: SocketServerTestCase.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
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); }
Example #25
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 #26
Source File: JobListener.java From kfs with GNU Affero General Public License v3.0 | 5 votes |
protected void initializeLogging(JobExecutionContext jobExecutionContext) { try { Calendar startTimeCalendar = dateTimeService.getCurrentCalendar(); StringBuilder nestedDiagnosticContext = new StringBuilder(StringUtils.substringAfter(BatchSpringContext.getJobDescriptor(jobExecutionContext.getJobDetail().getName()).getNamespaceCode(), "-").toLowerCase()).append(File.separator).append(jobExecutionContext.getJobDetail().getName()).append("-").append(dateTimeService.toDateTimeStringForFilename(dateTimeService.getCurrentDate())); ((Job) jobExecutionContext.getJobInstance()).setNdcAppender(new FileAppender(Logger.getRootLogger().getAppender("StdOut").getLayout(), getLogFileName(nestedDiagnosticContext.toString()))); ((Job) jobExecutionContext.getJobInstance()).getNdcAppender().addFilter(new NDCFilter(nestedDiagnosticContext.toString())); Logger.getRootLogger().addAppender(((Job) jobExecutionContext.getJobInstance()).getNdcAppender()); NDC.push(nestedDiagnosticContext.toString()); } catch (IOException e) { LOG.warn("Could not initialize special custom logging for job: " + jobExecutionContext.getJobDetail().getName(), e); } }
Example #27
Source File: BatchStepExecutor.java From kfs with GNU Affero General Public License v3.0 | 5 votes |
/** * Remove the appender and context from the NDC */ private void resetNDCLogging() { if ( ndcSet ) { ndcAppender.close(); Logger.getRootLogger().removeAppender(ndcAppender); NDC.pop(); } }
Example #28
Source File: RunnableWithNdc.java From tez with Apache License 2.0 | 5 votes |
@Override public final void run() { NDC.inherit(ndcStack); try { runInternal(); } finally { NDC.clear(); } }
Example #29
Source File: Log4jLogEvent.java From xian with Apache License 2.0 | 5 votes |
public String getValue(LogMessageField field) { switch (field.getNamedLogField()) { case Severity: return loggingEvent.getLevel().toString(); case ThreadName: return loggingEvent.getThreadName(); case SourceClassName: return getSourceClassName(); case SourceLineNumber: return getSourceLineNumber(); case SourceMethodName: return getSourceMethodName(); case SourceSimpleClassName: String sourceClassName = getSourceClassName(); if (sourceClassName == null) { return null; } return GelfUtil.getSimpleClassName(sourceClassName); case LoggerName: return loggingEvent.getLoggerName(); case NDC: String ndc = NDC.get(); if (ndc != null && !"".equals(ndc)) { return ndc; } return null; } throw new UnsupportedOperationException("Cannot provide value for " + field); }
Example #30
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)); }