/** * test whether the result of LogFormatter is the same as XMLFormatter * if there is no nested exception */ public void testXMLFormatterDifference(){ LogRecord rec = new LogRecord(Level.SEVERE, "PROBLEM"); LogFormatter logFormatter = new LogFormatter(); XMLFormatter xmlFormatter = new XMLFormatter(); String logResult = logFormatter.format(rec).replace("1000", "SEVERE"); String xmlResult = xmlFormatter.format(rec); assertEquals("WITHOUT THROWABLE", xmlResult, logResult); rec.setThrown(new NullPointerException("TESTING EXCEPTION")); rec.setResourceBundleName("MUJ BUNDLE"); logResult = logFormatter.format(rec); //remove file names logResult = logResult.replaceAll(" <file>.*</file>\n", "").replace("1000", "SEVERE"); xmlResult = xmlFormatter.format(rec); assertEquals("WITH THROWABLE", xmlResult, logResult); }
/** * Before the fix, JDK8 prints: {@code * <record> * <date>3913-11-18T17:35:40</date> * <millis>1384792540403</millis> * <sequence>0</sequence> * <level>INFO</level> * <thread>1</thread> * <message>test</message> * </record> * } * After the fix, it should print: {@code * <record> * <date>2013-11-18T17:35:40</date> * <millis>1384792696519</millis> * <sequence>0</sequence> * <level>INFO</level> * <thread>1</thread> * <message>test</message> * </record> * } * @param args the command line arguments */ public static void main(String[] args) { Locale locale = Locale.getDefault(); try { Locale.setDefault(Locale.ENGLISH); final GregorianCalendar cal1 = new GregorianCalendar(); final int year1 = cal1.get(Calendar.YEAR); LogRecord record = new LogRecord(Level.INFO, "test"); XMLFormatter formatter = new XMLFormatter(); final String formatted = formatter.format(record); System.out.println(formatted); final GregorianCalendar cal2 = new GregorianCalendar(); final int year2 = cal2.get(Calendar.YEAR); if (year2 < 1900) { throw new Error("Invalid system year: " + year2); } StringBuilder buf2 = new StringBuilder() .append("<date>").append(year2).append("-"); if (!formatted.contains(buf2.toString())) { StringBuilder buf1 = new StringBuilder() .append("<date>").append(year1).append("-"); if (formatted.contains(buf1) && year2 == year1 + 1 && cal2.get(Calendar.MONTH) == Calendar.JANUARY && cal2.get(Calendar.DAY_OF_MONTH) == 1) { // Oh! The year just switched in the midst of the test... System.out.println("Happy new year!"); } else { throw new Error("Expected year " + year2 + " not found in log:\n" + formatted); } } } finally { Locale.setDefault(locale); } }
public static void main(String[] args) { try { LogManager lm = LogManager.getLogManager(); Logger parentLogger, childLogger; FileHandler xmlHandler = new FileHandler("log_output.xml"); FileHandler htmlHandler = new FileHandler("log_output.html"); parentLogger = Logger.getLogger("ParentLogger"); childLogger = Logger.getLogger("ParentLogger.ChildLogger"); lm.addLogger(parentLogger); lm.addLogger(childLogger); parentLogger.setLevel(Level.WARNING); childLogger.setLevel(Level.ALL); xmlHandler.setFormatter(new XMLFormatter()); htmlHandler.setFormatter(new HTMLFormatter()); parentLogger.addHandler(xmlHandler); childLogger.addHandler(htmlHandler); childLogger.log(Level.FINE, "This is a fine log message"); childLogger.log(Level.SEVERE, "This is a severe log message"); xmlHandler.close(); htmlHandler.close(); } catch (Exception e) { System.err.println("Exception thrown: " + e); e.printStackTrace(); } }
static void test(Supplier<TimeStamp> timeStampSupplier) { TimeStamp t1 = timeStampSupplier.get(); int year1 = t1.getYear(); LogRecord record = new LogRecord(Level.INFO, "test"); XMLFormatter formatter = new XMLFormatter(); final String formatted = formatter.format(record); System.out.println(formatted); final TimeStamp t2 = timeStampSupplier.get(); final int year2 = t2.getYear(); if (year2 < 1900) { throw new Error("Invalid system year: " + year2); } final StringBuilder buf2 = new StringBuilder() .append("<date>").append(year2).append("-"); if (!formatted.contains(buf2.toString())) { StringBuilder buf1 = new StringBuilder() .append("<date>").append(year1).append("-"); if (formatted.contains(buf1) && year2 == year1 + 1 && t2.isJanuaryFirst()) { // Oh! The year just switched in the midst of the test... System.out.println("Happy new year!"); } else { throw new Error("Expected year " + year2 + " not found in log:\n" + formatted); } } }
@Override public void run() { // MemoryHandler check(new MemoryHandler(), Level.ALL, null, null, SimpleFormatter.class, ConfiguredHandler.class, 1000, Level.SEVERE); check(new MemoryHandler(new SpecifiedHandler(), 100, Level.WARNING), Level.ALL, null, null, SimpleFormatter.class, SpecifiedHandler.class, 100, Level.WARNING); // StreamHandler check(new StreamHandler(), Level.INFO, null, null, SimpleFormatter.class, null); check(new StreamHandler(System.out, new SpecifiedFormatter()), Level.INFO, null, null, SpecifiedFormatter.class, System.out); // ConsoleHandler check(new ConsoleHandler(), Level.INFO, null, null, SimpleFormatter.class, System.err); // SocketHandler (use the ServerSocket's port) try { check(new SocketHandler("localhost", serverSocket.getLocalPort()), Level.ALL, null, null, XMLFormatter.class); } catch (IOException e) { throw new RuntimeException("Can't connect to localhost:" + serverSocket.getLocalPort(), e); } }
@Test public void testOperatorSerialization() { Kryo kryo = new Kryo(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Output output = new Output(baos); kryo.writeObject(output, this.operator); output.close(); Input input = new Input(baos.toByteArray()); XMLFormatter tba1 = kryo.readObject(input, XMLFormatter.class); Assert.assertNotNull("XML parser not null", tba1); }
@Override public Logger getLogger(Class<?> c) { if (logger == null) { logger = Logger.getLogger(c.getName()); logger.addHandler(new StreamHandler(plainText, new SimpleFormatter())); logger.addHandler(new StreamHandler(xml, new XMLFormatter())); } return logger; }
/** * Sets the parameters for the static class. * * @param level the minimum level for error messages. If the severity of an error is lower than this value, nothing is logged. * @param dir the directory where the error log files are located * @param format the format of the log files (<code>txt</code> or <code>xml</code>) */ public static void setParameters(int level, String dir, String format) { switch (level) { case 2: logger.setLevel(Level.FINER); break; case 3: logger.setLevel(Level.FINE); break; case 4: logger.setLevel(Level.CONFIG); break; case 5: logger.setLevel(Level.INFO); break; case 6: logger.setLevel(Level.WARNING); break; case 7: logger.setLevel(Level.SEVERE); break; default: logger.setLevel(Level.FINEST); } java.util.Date dt = new java.util.Date(); SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss"); //$NON-NLS-1$ try { FileHandler handler = new FileHandler(dir + "log_" + df.format(dt) + "." + format, true);//$NON-NLS-1$ //$NON-NLS-2$ logger.addHandler(handler); logger.setUseParentHandlers(false); // don't log to console if (format.equals("txt")) //$NON-NLS-1$ handler.setFormatter(new SimpleFormatter()); else handler.setFormatter(new XMLFormatter()); } catch (Exception e) { ErrorLog.log(Messages.getString("ErrorLog.whileSetting"), 7, ErrorLog.class.getName(), "setParameters", e); //$NON-NLS-1$ //$NON-NLS-2$ System.exit(1); } }
/** * */ @Override protected void initFileHandler() throws Exception { CActivityFileHandler wFileHandler = new CActivityFileHandler( getFilePathPattern(), getFileLimit(), getFileCount()); wFileHandler.setFormatter(new XMLFormatter()); setFileHandler(wFileHandler); }
public boolean useInstant(XMLFormatter formatter) { return Boolean.parseBoolean(propertyFile.getProperty( formatter.getClass().getName()+".useInstant", "true")); }
public static void test(Properties props) { Configuration conf = Configuration.apply(props); LogRecord record = new LogRecord(Level.INFO, "Test Name: {0}"); record.setLoggerName("test"); record.setParameters(new Object[] {conf.testName()}); int nanos = record.getInstant().getNano() % NANOS_IN_MILLI; long millis = record.getMillis(); // make sure we don't have leading zeros when printing below // the second precision if (millis % MILLIS_IN_SECOND < 100) millis = millis + 100; // make sure we some nanos - and make sure we don't have // trailing zeros if (nanos % 10 == 0) nanos = nanos + 7; record.setMillis(millis); setNanoAdjustment(record, nanos); final Instant instant = record.getInstant(); if (nanos < 0) { throw new RuntimeException("Unexpected negative nano adjustment: " + getNanoAdjustment(record)); } if (nanos >= NANOS_IN_MILLI) { throw new RuntimeException("Nano adjustment exceeds 1ms: " + getNanoAdjustment(record)); } if (millis != record.getMillis()) { throw new RuntimeException("Unexpected millis: " + millis + " != " + record.getMillis()); } if (millis != record.getInstant().toEpochMilli()) { throw new RuntimeException("Unexpected millis: " + record.getInstant().toEpochMilli()); } long expectedNanos = (millis % MILLIS_IN_SECOND) * NANOS_IN_MILLI + nanos; assertEquals(expectedNanos, instant.getNano(), "Instant.getNano()"); XMLFormatter formatter = new XMLFormatter(); testMatching(formatter, record, instant, expectedNanos, conf.useInstant(formatter)); XMLFormatter custom = new CustomXMLFormatter(); testMatching(custom, record, instant, expectedNanos, conf.useInstant(custom)); }
private static void testMatching(XMLFormatter formatter, LogRecord record, Instant instant, long expectedNanos, boolean useInstant) { ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()); int zdtNanos = zdt.getNano(); assertEquals(expectedNanos, zdtNanos, "ZonedDateTime.getNano()"); String str = formatter.format(record); String match = "."+expectedNanos; if (str.contains(match) != useInstant) { throw new RuntimeException(formatter.getClass().getSimpleName() + ".format()" + " string does not contain expected nanos: " + "\n\texpected match for: '" + match + "'" + "\n\tin: \n" + str); } System.out.println("Found expected match for '"+match+"' in \n"+str); match = "<millis>"+instant.toEpochMilli()+"</millis>"; if (!str.contains(match)) { throw new RuntimeException(formatter.getClass().getSimpleName() + ".format()" + " string does not contain expected millis: " + "\n\texpected match for: '" + match + "'" + "\n\tin: \n" + str); } System.out.println("Found expected match for '"+match+"' in \n"+str); match = "<nanos>"; if (str.contains(match) != useInstant) { throw new RuntimeException(formatter.getClass().getSimpleName() + ".format()" + " string " + (useInstant ? "does not contain expected nanos: " : "contains unexpected nanos: ") + "\n\t" + (useInstant ? "expected" : "unexpected") + " match for: '" + match + "'" + "\n\tin: \n" + str); } match = "<nanos>"+getNanoAdjustment(record)+"</nanos>"; if (str.contains(match) != useInstant) { throw new RuntimeException(formatter.getClass().getSimpleName() + ".format()" + " string " + (useInstant ? "does not contain expected nanos: " : "contains unexpected nanos: ") + "\n\t" + (useInstant ? "expected" : "unexpected") + " match for: '" + match + "'" + "\n\tin: \n" + str); } if (useInstant) { System.out.println("Found expected match for '"+match+"' in \n"+str); } else { System.out.println("As expected '"+match+"' is not present in \n"+str); } match = useInstant ? DateTimeFormatter.ISO_INSTANT.format(instant) : zdt.truncatedTo(ChronoUnit.SECONDS) .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); match = "<date>"+match+"</date>"; if (!str.contains(match)) { throw new RuntimeException(formatter.getClass().getSimpleName() + ".format()" + " string does not contain expected date: " + "\n\texpected match for: '" + match + "'" + "\n\tin: \n" + str); } System.out.println("Found expected match for '"+match+"' in \n"+str); }
protected void setUp() throws Exception { super.setUp(); formatter = new XMLFormatter(); handler = new MockHandler(); lr = new LogRecord(Level.SEVERE, "pattern"); }
@Override protected void setUp() throws Exception { super.setUp(); formatter = new XMLFormatter(); handler = new MockHandler(); lr = new LogRecord(Level.SEVERE, "pattern"); }