public void assertMessages(final String msg, final int size, final String methodName) { final ListAppender appender = ctx.getListAppender("ClassAndMethod"); assertEquals(msg + ".size", size, appender.getMessages().size()); for (final String message : appender.getMessages()) { assertEquals( msg + " has incorrect caller info", this.getClass().getName() + '.' + methodName, message); } }
@Test public void test() throws Exception { // To ensure our custom plugin is NOT included in the log4j plugin metadata file, // we make sure the class does not exist until after the build is finished. // So we don't create the custom plugin class until this test is run. final File orig = new File("target/test-classes/customplugin/FixedStringLayout.java.source"); final File f = new File(orig.getParentFile(), "FixedStringLayout.java"); assertTrue("renamed source file OK", orig.renameTo(f)); compile(f); assertTrue("reverted source file OK", f.renameTo(orig)); // load the compiled class Class.forName("customplugin.FixedStringLayout"); // now that the custom plugin class exists, we load the config // with the packages element pointing to our custom plugin ctx = Configurator.initialize("Test1", "customplugin/log4j2-741.xml"); config = ctx.getConfiguration(); listAppender = (ListAppender) config.getAppender("List"); final Logger logger = LogManager.getLogger(PluginManagerPackagesTest.class); logger.info("this message is ignored"); final List<String> messages = listAppender.getMessages(); assertEquals(messages.toString(), 1, messages.size()); assertEquals("abc123XYZ", messages.get(0)); }
@Test public void testLogWithCallingClass() throws Exception { final Logger log = Logger.getLogger("Test.CallerClass"); log.config("Calling from LoggerTest"); final List<String> messages = stringAppender.getMessages(); assertThat(messages, hasSize(1)); final String message = messages.get(0); assertEquals(AbstractLoggerTest.class.getName(), message); }
@Test public void testReplacement() { // See org.fusesource.jansi.AnsiRenderer logger.error("@|red,bold Warning!|@ Pants on @|red fire!|@"); final List<String> msgs = app.getMessages(); assertNotNull(msgs); assertEquals("Incorrect number of messages. Should be 1 is " + msgs.size(), 1, msgs.size()); assertTrue( "Replacement failed - expected ending " + EXPECTED + ", actual " + msgs.get(0), msgs.get(0).endsWith(EXPECTED)); }