@Test public void testNDC() throws Exception { initialize("TestJsonLayout/default.properties"); NDC.push("frist"); // misspelling intentional NDC.push("second"); logger.debug(TEST_MESSAGE); NDC.clear(); captureLoggingOutput(); assertCommonElements(TEST_MESSAGE); DomAsserts.assertEquals("ndc", "frist second", dom, "/data/ndc"); }
@Override public final void run() { try { NDC.inherit(loggingContext); CurrentUser.setUserState(callingThreadsAuthentication); CurrentInstitution.set(callingThreadsInstitution); doRun(); } finally { CurrentInstitution.remove(); CurrentUser.setUserState(null); NDC.remove(); } }
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; }
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(); } }
/** * 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()); }
/** * 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")); } }
/** * 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")); } }
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(); } }
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(); } }
public UserDomainObject verifyUser(String login, String password) { NDC.push("verifyUser"); try { UserDomainObject result = null; boolean userAuthenticates = externalizedImcmsAuthAndMapper.authenticate(login, password); UserDomainObject user = externalizedImcmsAuthAndMapper.getUser(login); if (null == user) { mainLog.info("->User '" + login + "' failed to log in: User not found."); } else if (!user.isActive()) { logUserDeactivated(user); } else if (!userAuthenticates) { mainLog.info("->User '" + login + "' failed to log in: Wrong password."); } else { result = user; logUserLoggedIn(user); } return result; } finally { NDC.pop(); } }
/** * @return {@code true} if the object contains just the date, false otherwise. */ private boolean isDateOnly(EventDateTime source) { NDC.push("isDateOnly"); try { if (source.getDate() != null && source.getDateTime() == null) { return true; } if (source.getDate() == null && source.getDateTime() != null) { return false; } logger.error("source: " + source); logger.error("date: " + source.getDate()); logger.error("time: " + source.getDateTime()); throw new IllegalArgumentException("API must have changed, both Date and DateTime are returned, need to revise the code"); } finally { NDC.pop(); } }
@Override public void networkFault(OneWireNetworkEvent e, String message) { NDC.push("networkFault"); try { // This is an event pertinent to everyone consume(new DataSample<Double>( System.currentTimeMillis(), type + getAddress(), type + getAddress(), null, new OneWireIOException(message))); } finally { NDC.pop(); } }
/** * Make sure the signal given to {@link #consume(DataSample)} is sane. * * @param signal Signal to check. */ private void check(DataSample<Double> signal) { NDC.push("check"); try { if (signal == null) { throw new IllegalArgumentException("signal can't be null"); } if (signal.isError()) { logger.error("Should not have propagated all the way here", signal.error); throw new IllegalArgumentException("Error signal should have been handled by zone controller"); } if (signal.sample < 0.0) { throw new IllegalArgumentException("Signal must be non-negative, received " + signal.sample); } } finally { NDC.pop(); } }
/** * {@inheritDoc} */ public void consume(DataSample<ProcessControllerStatus> signal) { // Let them consume the common process controller signal components super.consume(signal); // And now let's take care of PID specific components NDC.push("consume.pid"); try { // This is a bit dangerous, but let's see how exactly dangerous PidControllerStatus pidStatus = (PidControllerStatus) signal.sample; long timestamp = signal.timestamp; String sourceName = signal.sourceName; consume(timestamp, sourceName + ".p", pidStatus.p); consume(timestamp, sourceName + ".i", pidStatus.i); consume(timestamp, sourceName + ".d", pidStatus.d); } finally { NDC.pop(); } }
/** * Load the configuration already present in the jar file. * * With some luck, all objects instantiated here will be garbage collected * pretty soon and won't matter. * * If this bothers you, remove the method invocation and recompile. * * @see #CF_EMBEDDED */ private void loadSampleConfiguration() { NDC.push("loadSampleConfiguration"); try { // We don't need it for anything other than loading a sample, // hence local scope. ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { CF_EMBEDDED }); // This class is the root of the instantiation hierarchy - // if it can be instantiated, then everything else is fine @SuppressWarnings("unused") DamperController dc = (DamperController) applicationContext.getBean("damper_controller-sample1"); } catch (NoSuchBeanDefinitionException ex) { logger.debug("Oh, they found and deleted the sample configuration! Good."); } finally { NDC.pop(); } }
/** * Make sure the {@link ShellSensor} properly executes a shell command given. */ public void testGood() throws IOException { NDC.push("testGood"); try { if (!isOsSupported()) { return; } // VT: NOTE: The test string is Unix specific (shell builtin) ShellSensor ss = new ShellSensor("address", 1000, "echo 5.5"); DataSample<Double> sample = ss.getSensorSignal(); logger.info("Sample: " + sample); assertFalse(sample.isError()); assertEquals(5.5, sample.sample); } finally { NDC.pop(); } }
public synchronized void setBaudRate(int baudRate) throws IOException { NDC.push("setBaudRate(" + baudRate + ")"); try { if(!isPortOpen()) throw new IOException(null, new IllegalStateException("Port Not Open")); try { // set baud rate serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); logger.debug("Set baudRate=" + baudRate); } catch(UnsupportedCommOperationException ex) { throw new IOException("Failed to set baud rate: ", ex); } } 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(); } }
/** * 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)); }
/** * 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 void uncaughtException(Thread t, Throwable e) { String className = e.getClass().getCanonicalName() + "\n"; StringBuilder stackTrace = new StringBuilder(className); for (StackTraceElement el : e.getStackTrace()) { stackTrace.append("at ").append(el).append('\n'); } String msg = ""; StringBuilder sb = new StringBuilder(); File logFile; String logName = Log.getCurrentLogFile(); if (logName != null && (logFile = new File(logName)).canRead()) { Log.error("Runtime exception", e); try (BufferedReader input = Files.newBufferedReader(logFile.toPath(), StandardCharsets.UTF_8)) { String line; while ((line = input.readLine()) != null) { sb.append(line).append('\n'); } NDC.push(sb.toString()); } catch (IOException ex) { ex.printStackTrace(); } } else { System.err.println("Runtime exception"); System.err.println(stackTrace); msg += "Uncaught Exception in " + JHVGlobals.userAgent; msg += "\nDate: " + new Date(); msg += "\nThread: " + t; msg += "\nMessage: " + e.getMessage(); msg += "\nStacktrace:\n"; msg += stackTrace + "\n"; } Log.fatal(null, e); showErrorDialog(msg + "Log:\n" + sb); }
/** * Push DNC context for proper log4j logging of different threads * @param servletSessionId the user session id * @param userSessionId the user session id * @param userID the unique user id */ public static void pushDNC( final HttpServletRequest request, final String userSessionId, final int userID ) { NDC.push( "IP: " + HTTPUtils.getTrueRemoteAddr(userID, request) ); NDC.push( "(U)ID: " + userID ); final String id = ( userSessionId != null ? userSessionId : "null"); NDC.push( "(U)session: " + id ); }
/** * Cleanes DNC context does pop and remove */ public static void cleanDNC() { NDC.pop(); NDC.pop(); NDC.pop(); NDC.remove(); }
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(); }
/** * 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); }
/** * Clear MDC and NDC before test. */ public void setUp() { NDC.clear(); if (MDC.getContext() != null) { MDC.getContext().clear(); } }
/** * 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")); } }
/** * 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")); } }
/** * 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); }
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"); }