@Test public void testFlushAtEndOfBatch() throws Exception { final File f = new File("target", "RandomAccessFileAppenderTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Message flushed with immediate flush=false"; log.info(msg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); reader.close(); f.delete(); assertNotNull("line1", line1); assertTrue("line1 incorrect", line1.contains(msg)); final String location = "testFlushAtEndOfBatch"; assertTrue("no location", !line1.contains(location)); }
@Test public void testFlushAtEndOfBatch() throws Exception { final File f = new File("target", "RollingRandomAccessFileAppenderTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Message flushed with immediate flush=false"; log.info(msg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); reader.close(); f.delete(); assertNotNull("line1", line1); assertTrue("line1 correct", line1.contains(msg)); final String location = "testFlushAtEndOfBatch"; assertTrue("no location", !line1.contains(location)); }
@Test public void testLocationIncluded() throws Exception { final File f = new File("target", "RollingRandomAccessFileAppenderLocationTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Message with location, flushed with immediate flush=false"; log.info(msg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); reader.close(); f.delete(); assertNotNull("line1", line1); assertTrue("line1 correct", line1.contains(msg)); final String location = "testLocationIncluded"; assertTrue("has location", line1.contains(location)); }
@Test public void testLocationIncluded() throws Exception { final File f = new File("target", "RandomAccessFileAppenderLocationTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Message with location, flushed with immediate flush=false"; log.info(msg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); reader.close(); f.delete(); assertNotNull("line1", line1); assertTrue("line1 correct", line1.contains(msg)); final String location = "testLocationIncluded"; assertTrue("has location", line1.contains(location)); }
@Test public void testAdditivity() throws Exception { final File f = new File("target", "AsyncLoggerConfigTest.log"); assertTrue("Deleted old file before test", !f.exists() || f.delete()); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Additive logging: 2 for the price of 1!"; log.info(msg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); final String line2 = reader.readLine(); reader.close(); f.delete(); assertNotNull("line1", line1); assertNotNull("line2", line2); assertTrue("line1 correct", line1.contains(msg)); assertTrue("line2 correct", line2.contains(msg)); final String location = "testAdditivity"; assertTrue("location", line1.contains(location) || line2.contains(location)); }
@Test public void testAsyncLogWritesToLog() throws Exception { final File f = new File("target", "AsyncLoggerTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Async logger msg"; log.info(msg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); reader.close(); f.delete(); assertNotNull("line1", line1); assertTrue("line1 correct", line1.contains(msg)); final String location = "testAsyncLogWritesToLog"; assertTrue("no location", !line1.contains(location)); }
@Test public void testAsyncLogWritesToLog() throws Exception { final File f = new File("target", "AsyncLoggerLocationTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Async logger msg with location"; log.info(msg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); reader.close(); f.delete(); assertNotNull("line1", line1); assertTrue("line1 correct", line1.contains(msg)); final String location = "testAsyncLogWritesToLog"; assertTrue("has location", line1.contains(location)); }
/** * Loads the LoggerContext using the ContextSelector. * @param fqcn The fully qualified class name of the caller. * @param loader The ClassLoader to use or null. * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext. * @param currentContext If true returns the current Context, if false returns the Context appropriate * for the caller if a more appropriate Context can be determined. * @param source The configuration source. * @return The LoggerContext. */ public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext, final boolean currentContext, final ConfigurationSource source) { final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, null); if (externalContext != null && ctx.getExternalContext() == null) { ctx.setExternalContext(externalContext); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { if (source != null) { ContextAnchor.THREAD_CONTEXT.set(ctx); final Configuration config = ConfigurationFactory.getInstance().getConfiguration(ctx, source); LOGGER.debug("Starting LoggerContext[name={}] from configuration {}", ctx.getName(), source); ctx.start(config); ContextAnchor.THREAD_CONTEXT.remove(); } else { ctx.start(); } } return ctx; }
/** * Loads the LoggerContext using the ContextSelector using the provided Configuration * @param fqcn The fully qualified class name of the caller. * @param loader The ClassLoader to use or null. * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext. * @param currentContext If true returns the current Context, if false returns the Context appropriate * for the caller if a more appropriate Context can be determined. * @param configuration The Configuration. * @return The LoggerContext. */ public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext, final boolean currentContext, final Configuration configuration) { final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, null); if (externalContext != null && ctx.getExternalContext() == null) { ctx.setExternalContext(externalContext); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { ContextAnchor.THREAD_CONTEXT.set(ctx); try { ctx.start(configuration); } finally { ContextAnchor.THREAD_CONTEXT.remove(); } } return ctx; }
/** * Loads the LoggerContext using the ContextSelector. * @param fqcn The fully qualified class name of the caller. * @param loader The ClassLoader to use or null. * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext. * @param currentContext If true returns the current Context, if false returns the Context appropriate * for the caller if a more appropriate Context can be determined. * @param configLocation The location of the configuration for the LoggerContext (or null). * @return The LoggerContext. */ @Override public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext, final boolean currentContext, final URI configLocation, final String name) { final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, configLocation); if (externalContext != null && ctx.getExternalContext() == null) { ctx.setExternalContext(externalContext); } if (name != null) { ctx.setName(name); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { if (configLocation != null || name != null) { ContextAnchor.THREAD_CONTEXT.set(ctx); final Configuration config = ConfigurationFactory.getInstance().getConfiguration(ctx, name, configLocation); LOGGER.debug("Starting LoggerContext[name={}] from configuration at {}", ctx.getName(), configLocation); ctx.start(config); ContextAnchor.THREAD_CONTEXT.remove(); } else { ctx.start(); } } return ctx; }
public void setTriggeringPolicy(final TriggeringPolicy triggeringPolicy) { triggeringPolicy.initialize(this); final TriggeringPolicy policy = this.triggeringPolicy; int count = 0; boolean policyUpdated = false; do { ++count; } while (!(policyUpdated = triggeringPolicyUpdater.compareAndSet(this, this.triggeringPolicy, triggeringPolicy)) && count < MAX_TRIES); if (policyUpdated) { if (triggeringPolicy instanceof LifeCycle) { ((LifeCycle) triggeringPolicy).start(); } if (policy instanceof LifeCycle) { ((LifeCycle) policy).stop(); } } else { if (triggeringPolicy instanceof LifeCycle) { ((LifeCycle) triggeringPolicy).stop(); } } }
@Test public void testPropertiesConfiguration() { final Configuration config = context.getConfiguration(); assertNotNull("No configuration created", config); assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED); final Map<String, Appender> appenders = config.getAppenders(); assertNotNull(appenders); assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1); final Map<String, LoggerConfig> loggers = config.getLoggers(); assertNotNull(loggers); assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2); final Filter filter = config.getFilter(); assertNotNull("No Filter", filter); assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!"); }
@Test public void testPropertiesConfiguration() { final Configuration config = context.getConfiguration(); assertNotNull("No configuration created", config); assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED); final Map<String, Appender> appenders = config.getAppenders(); assertNotNull(appenders); assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1); final Map<String, LoggerConfig> loggers = config.getLoggers(); assertNotNull(loggers); assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 1); final Filter filter = config.getFilter(); assertNotNull("No Filter", filter); assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!"); }
@Test public void testPropertiesConfiguration() { final Configuration config = context.getConfiguration(); assertNotNull("No configuration created", config); assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED); final Map<String, Appender> appenders = config.getAppenders(); assertNotNull(appenders); assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1); final Map<String, LoggerConfig> loggers = config.getLoggers(); assertNotNull(loggers); assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2); final Filter filter = config.getFilter(); assertNotNull("No Filter", filter); assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter); final Logger logger = LogManager.getLogger(getClass()); assertEquals("Incorrect level " + logger.getLevel(), Level.DEBUG, logger.getLevel()); logger.debug("Welcome to Log4j!"); }
@Test public void testPropertiesConfiguration() { final Configuration config = context.getConfiguration(); assertNotNull("No configuration created", config); assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED); final Map<String, Appender> appenders = config.getAppenders(); assertNotNull(appenders); assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 3); final Map<String, LoggerConfig> loggers = config.getLoggers(); assertNotNull(loggers); assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2); final Filter filter = config.getFilter(); assertNotNull("No Filter", filter); assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!"); }
@Override public void stop() throws LifecycleException { log("stopping Context"); if (!started) { throw new LifecycleException("SimpleContext has already stopped"); } this.lifecycle.fireLifecycleEvent(BEFORE_STOP_EVENT, null); started = false; if (loader != null && loader instanceof LifeCycle) { ((LifeCycle) loader).stop(); } if (pipeline != null && pipeline instanceof LifeCycle) { ((LifeCycle) pipeline).stop(); } Container[] children = findChildren(); for (int i = 0; i < children.length; ++i) { if (children[i] instanceof LifeCycle) { ((Lifecycle) children[i]).stop(); } } this.lifecycle.fireLifecycleEvent(STOP_EVENT, null); this.lifecycle.fireLifecycleEvent(AFTER_STOP_EVENT, null); log("Context stopped"); }
@Override public void onApplicationEvent(final ContextClosedEvent event) { logger.info("Gracefully shutting down application."); manager.stop(); try { manager.tearDown(); logger.info("JOAL gracefully shut down."); } catch (final IOException e) { logger.error("Failed to gracefully shut down JOAL.", e); } // Since we disabled log4j2 shutdown hook, we need to handle it manually. final LifeCycle loggerContext = (LoggerContext) LogManager.getContext(false); loggerContext.stop(); }
public void recycle() { if (factory != null) factory.recycle(); JedisManager.getInstance().close(); ((LifeCycle) LogManager.getContext()).stop(); }
/** * Perform whatever cleanup is required of the underlying object.. */ @Override public void close() { LifeCycle lc = ((LifeCycle)LogManager.getContext()); if (lc.isStarted()) { lc.stop(); } }
private void cleanupFilter(final AppenderControl ctl) { final Filter filter = ctl.getFilter(); if (filter != null) { ctl.removeFilter(filter); if (filter instanceof LifeCycle) { ((LifeCycle) filter).stop(); } } }
@Override public void start() { for (final Filter filter : filters) { if (filter instanceof LifeCycle) { ((LifeCycle) filter).start(); } } isStarted = true; }
@Override public void stop() { for (final Filter filter : filters) { if (filter instanceof LifeCycle) { ((LifeCycle) filter).stop(); } } isStarted = false; }
@Test public void testFlushAtEndOfBatch() throws Exception { final File f = new File("target", "XmlFileAppenderTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String logMsg = "Message flushed with immediate flush=false"; log.info(logMsg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); String line1; String line2; String line3; try { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); } finally { reader.close(); f.delete(); } assertNotNull("line1", line1); assertNotNull("line1", line1); final String msg1 = "<log4j:Event "; assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + "]", line1.contains(msg1)); assertNotNull("line2", line2); final String msg2 = logMsg; assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + "]", line2.contains(msg2)); assertNotNull("line3", line3); final String msg3 = "</log4j:Event>"; assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + "]", line3.contains(msg3)); final String location = "testFlushAtEndOfBatch"; assertTrue("no location", !line1.contains(location)); }
@Test public void testFlushAtEndOfBatch() throws Exception { final File file = new File("target", "XmlCompactFileAppenderTest.log"); file.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String logMsg = "Message flushed with immediate flush=false"; log.info(logMsg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(file)); String line1; try { line1 = reader.readLine(); } finally { reader.close(); file.delete(); } assertNotNull("line1", line1); final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + "]", line1.contains(msg1)); final String msg2 = "<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">"; assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg2 + "]", line1.contains(msg2)); final String msg3 = "<Event "; assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg3 + "]", line1.contains(msg3)); final String msg4 = logMsg; assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg4 + "]", line1.contains(msg4)); final String location = "testFlushAtEndOfBatch"; assertTrue("no location", !line1.contains(location)); assertTrue(line1.indexOf('\r') == -1); assertTrue(line1.indexOf('\n') == -1); }
@Test public void validateXmlSchemaSimple() throws Exception { final File file = new File("target", "XmlCompactFileAsyncAppenderValidationTest.log.xml"); file.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); log.warn("Message 1"); log.info("Message 2"); log.debug("Message 3"); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread this.validateXmlSchema(file); }
@Test public void validateXmlSchemaNoEvents() throws Exception { final File file = new File("target", "XmlCompactFileAsyncAppenderValidationTest.log.xml"); file.delete(); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread this.validateXmlSchema(file); }
@Test public void testConsecutiveReconfigure() throws Exception { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest2.xml"); final File f = new File("target", "AsyncLoggerConfigTest2.log"); assertTrue("Deleted old file before test", !f.exists() || f.delete()); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Message before reconfig"; log.info(msg); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); ctx.reconfigure(); ctx.reconfigure(); final String msg2 = "Message after reconfig"; log.info(msg2); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); final String line2 = reader.readLine(); reader.close(); f.delete(); assertNotNull("line1", line1); assertNotNull("line2", line2); assertTrue("line1 " + line1, line1.contains(msg)); assertTrue("line2 " + line2, line2.contains(msg2)); }
@Test public void testNewInstanceReturnsAsyncLogger() { final Logger logger = new AsyncLoggerContext("a").newInstance( new LoggerContext("a"), "a", null); assertTrue(logger instanceof AsyncLogger); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread }
private void validate(final Configuration config) { assertNotNull(config); assertNotNull(config.getName()); assertFalse(config.getName().isEmpty()); assertNotNull("No configuration created", config); assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED); final Map<String, Appender> appenders = config.getAppenders(); assertNotNull(appenders); assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 2); final KafkaAppender kafkaAppender = (KafkaAppender) appenders.get("Kafka"); final GelfLayout gelfLayout = (GelfLayout) kafkaAppender.getLayout(); final Map<String, LoggerConfig> loggers = config.getLoggers(); assertNotNull(loggers); assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2); final LoggerConfig rootLoggerConfig = loggers.get(""); assertEquals(Level.ERROR, rootLoggerConfig.getLevel()); assertFalse(rootLoggerConfig.isIncludeLocation()); final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j"); assertEquals(Level.DEBUG, loggerConfig.getLevel()); assertTrue(loggerConfig.isIncludeLocation()); final Filter filter = config.getFilter(); assertNotNull("No Filter", filter); assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter); final List<CustomLevelConfig> customLevels = config.getCustomLevels(); assertNotNull("No CustomLevels", filter); assertEquals(1, customLevels.size()); final CustomLevelConfig customLevel = customLevels.get(0); assertEquals("Panic", customLevel.getLevelName()); assertEquals(17, customLevel.getIntLevel()); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!"); }
/** * Loads the LoggerContext using the ContextSelector. * @param fqcn The fully qualified class name of the caller. * @param loader The ClassLoader to use or null. * @param currentContext If true returns the current Context, if false returns the Context appropriate * for the caller if a more appropriate Context can be determined. * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext. * @return The LoggerContext. */ @Override public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext, final boolean currentContext) { final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext); if (externalContext != null && ctx.getExternalContext() == null) { ctx.setExternalContext(externalContext); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { ctx.start(); } return ctx; }
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext, final boolean currentContext, final List<URI> configLocations, final String name) { final LoggerContext ctx = selector .getContext(fqcn, loader, currentContext, null/*this probably needs to change*/); if (externalContext != null && ctx.getExternalContext() == null) { ctx.setExternalContext(externalContext); } if (name != null) { ctx.setName(name); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { if ((configLocations != null && !configLocations.isEmpty())) { ContextAnchor.THREAD_CONTEXT.set(ctx); final List<AbstractConfiguration> configurations = new ArrayList<>(configLocations.size()); for (final URI configLocation : configLocations) { final Configuration currentReadConfiguration = ConfigurationFactory.getInstance() .getConfiguration(ctx, name, configLocation); if (currentReadConfiguration instanceof AbstractConfiguration) { configurations.add((AbstractConfiguration) currentReadConfiguration); } else { LOGGER.error( "Found configuration {}, which is not an AbstractConfiguration and can't be handled by CompositeConfiguration", configLocation); } } final CompositeConfiguration compositeConfiguration = new CompositeConfiguration(configurations); LOGGER.debug("Starting LoggerContext[name={}] from configurations at {}", ctx.getName(), configLocations); ctx.start(compositeConfiguration); ContextAnchor.THREAD_CONTEXT.remove(); } else { ctx.start(); } } return ctx; }
@Override public boolean stop(final long timeout, final TimeUnit timeUnit) { setStopping(); boolean stopped = true; for (final TriggeringPolicy triggeringPolicy : triggeringPolicies) { if (triggeringPolicy instanceof LifeCycle2) { stopped &= ((LifeCycle2) triggeringPolicy).stop(timeout, timeUnit); } else if (triggeringPolicy instanceof LifeCycle) { ((LifeCycle) triggeringPolicy).stop(); stopped &= true; } } setStopped(); return stopped; }
public void initialize() { if (!initialized) { LOGGER.debug("Initializing triggering policy {}", triggeringPolicy); initialized = true; triggeringPolicy.initialize(this); if (triggeringPolicy instanceof LifeCycle) { ((LifeCycle) triggeringPolicy).start(); } } }
private void validate(final Configuration config) { assertNotNull(config); assertNotNull(config.getName()); assertFalse(config.getName().isEmpty()); assertNotNull("No configuration created", config); assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED); final Map<String, Appender> appenders = config.getAppenders(); assertNotNull(appenders); assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1); final ConsoleAppender consoleAppender = (ConsoleAppender)appenders.get("Stdout"); final PatternLayout gelfLayout = (PatternLayout)consoleAppender.getLayout(); final Map<String, LoggerConfig> loggers = config.getLoggers(); assertNotNull(loggers); assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2); final LoggerConfig rootLoggerConfig = loggers.get(""); assertEquals(Level.ERROR, rootLoggerConfig.getLevel()); assertFalse(rootLoggerConfig.isIncludeLocation()); final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j"); assertEquals(Level.DEBUG, loggerConfig.getLevel()); assertTrue(loggerConfig.isIncludeLocation()); final Filter filter = config.getFilter(); assertNotNull("No Filter", filter); assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter); final List<CustomLevelConfig> customLevels = config.getCustomLevels(); assertNotNull("No CustomLevels", filter); assertEquals(1, customLevels.size()); final CustomLevelConfig customLevel = customLevels.get(0); assertEquals("Panic", customLevel.getLevelName()); assertEquals(17, customLevel.getIntLevel()); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!"); }
/** * Make the Filter available for use. */ public void startFilter() { if (filter != null && filter instanceof LifeCycle) { ((LifeCycle) filter).start(); } }
/** * Cleanup the Filter. */ public void stopFilter() { if (filter != null && filter instanceof LifeCycle) { ((LifeCycle) filter).stop(); } }
@Test public void testRollover() throws Exception { final File f = new File("target", "RollingRandomAccessFileAppenderTest.log"); // System.out.println(f.getAbsolutePath()); final File after1 = new File("target", "afterRollover-1.log"); f.delete(); after1.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "First a short message that does not trigger rollover"; log.info(msg); Thread.sleep(50); BufferedReader reader = new BufferedReader(new FileReader(f)); final String line1 = reader.readLine(); assertTrue(line1.contains(msg)); reader.close(); assertFalse("afterRollover-1.log not created yet", after1.exists()); String exceed = "Long message that exceeds rollover size... "; final char[] padding = new char[250]; Arrays.fill(padding, 'X'); exceed += new String(padding); log.warn(exceed); assertFalse("exceeded size but afterRollover-1.log not created yet", after1.exists()); final String trigger = "This message triggers rollover."; log.warn(trigger); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread assertTrue("afterRollover-1.log created", after1.exists()); reader = new BufferedReader(new FileReader(f)); final String new1 = reader.readLine(); assertTrue("after rollover only new msg", new1.contains(trigger)); assertNull("No more lines", reader.readLine()); reader.close(); f.delete(); reader = new BufferedReader(new FileReader(after1)); final String old1 = reader.readLine(); assertTrue("renamed file line 1", old1.contains(msg)); final String old2 = reader.readLine(); assertTrue("renamed file line 2", old2.contains(exceed)); final String line = reader.readLine(); assertNull("No more lines", line); reader.close(); after1.delete(); }
@Test public void testFlushAtEndOfBatch() throws Exception { final File file = new File("target", "JSONCompleteFileAppenderTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String logMsg = "Message flushed with immediate flush=true"; log.info(logMsg); log.error(logMsg, new IllegalArgumentException("badarg")); ((LifeCycle) LogManager.getContext()).stop(); // stops async thread try { final BufferedReader reader = new BufferedReader(new FileReader(file)); String line1; String line2; String line3; String line4; String line5; try { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); line4 = reader.readLine(); line5 = reader.readLine(); } finally { reader.close(); } assertNotNull("line1", line1); final String msg1 = "["; assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + "]", line1.equals(msg1)); assertNotNull("line2", line2); final String msg2 = " {"; assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + "]", line2.equals(msg2)); assertNotNull("line3", line3); final String msg3 = " \"logger\":\"com.foo.Bar\","; assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + "]", line3.contains(msg3)); assertNotNull("line4", line4); final String msg4 = "\"timestamp\":"; assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + "]", line4.contains(msg4)); assertNotNull("line5", line5); final String msg5 = " \"level\":\"INFO\","; assertTrue("line5 incorrect: [" + line5 + "], does not contain: [" + msg5 + "]", line5.contains(msg5)); final String location = "testFlushAtEndOfBatch"; assertTrue("no location", !line1.contains(location)); if (false) { // now check that we can parse the array ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); assertNotNull(engine); // stopping the logger context does not seem to flush the file... Object eval = engine.eval(new FileReader(file)); assertNotNull(eval); } } finally { file.delete(); } }
@Test @Ignore public void testFlushAtEndOfBatch() throws Exception { final File f = new File("target", "XmlRandomAccessFileAppenderTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String logMsg = "Message flushed with immediate flush=false"; log.info(logMsg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); String line1; String line2; String line3; String line4; try { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); line4 = reader.readLine(); } finally { reader.close(); f.delete(); } assertNotNull("line1", line1); final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + "]", line1.equals(msg1)); assertNotNull("line2", line2); final String msg2 = "<log4j:events xmlns:log4j=\"http://logging.apache.org/log4j/\">"; assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + "]", line2.equals(msg2)); assertNotNull("line3", line3); final String msg3 = "<log4j:event "; assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + "]", line3.contains(msg3)); assertNotNull("line4", line4); final String msg4 = logMsg; assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + "]", line4.contains(msg4)); final String location = "testFlushAtEndOfBatch"; assertTrue("no location", !line1.contains(location)); }
@Test public void testFlushAtEndOfBatch() throws Exception { final File f = new File("target", "XmlCompleteFileAppenderTest.log"); // System.out.println(f.getAbsolutePath()); f.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final String logMsg = "Message flushed with immediate flush=false"; log.info(logMsg); ((LifeCycle) LogManager.getContext()).stop(); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(f)); String line1; String line2; String line3; String line4; try { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); line4 = reader.readLine(); } finally { reader.close(); f.delete(); } assertNotNull("line1", line1); final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + "]", line1.equals(msg1)); assertNotNull("line2", line2); final String msg2 = "<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">"; assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + "]", line2.equals(msg2)); assertNotNull("line3", line3); final String msg3 = "<Event "; assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + "]", line3.contains(msg3)); assertNotNull("line4", line4); final String msg4 = logMsg; assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + "]", line4.contains(msg4)); final String location = "testFlushAtEndOfBatch"; assertTrue("no location", !line1.contains(location)); }