private void initializeLogging(final Level logLevel) { final LoggerContext context = (LoggerContext) LogManager.getContext(false); final org.apache.logging.log4j.core.config.Configuration config = context.getConfiguration(); config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(logLevel); config.getLoggerConfig(Main.class.getPackage().getName()).setLevel(logLevel); context.updateLoggers(config); }
@Test public void testNoProps() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); final Configuration config = ctx.getConfiguration(); assertTrue("Configuration is not an XmlConfiguration", config instanceof XmlConfiguration); }
@Test(timeout = 5000) public void shutdownTest() throws Exception { final LoggerContext ctx = (LoggerContext)LogManager.getContext(false); final Logger logger = ctx.getLogger("Logger"); logger.info("This is a test"); ctx.stop(); }
LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(level); ctx.updateLoggers(); // This causes all Loggers to refetch information from their LoggerConfig.
@VisibleForTesting protected void setLoggerLevel(final String loggerName, final Level level) { final LoggerContext context = (LoggerContext) LogManager.getContext(false); final Configuration config = context.getConfiguration(); final LoggerConfig loggerConfig = config.getLoggerConfig(loggerName); if(loggerName.equals(loggerConfig.getName())) { loggerConfig.setLevel(level); } else { final LoggerConfig newLoggerConfig = new LoggerConfig(loggerName, level, loggerConfig.isAdditive()); newLoggerConfig.setLevel(level); config.addLogger(loggerName, newLoggerConfig); } context.updateLoggers(); }
LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(FsCrawlerCli.class.getPackage().getName()); logger.warn("--debug or --trace can't be used when --silent is set. Only silent mode will be activated."); logger.warn("--silent is set but no job has been defined. Add a job name or remove --silent option. Exiting."); jCommander.usage(); return; LoggerConfig rootLogger = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(Level.OFF); rootLogger.setLevel(Level.OFF); } else { loggerConfig.setLevel(commands.debug ? Level.DEBUG : Level.TRACE); ctx.updateLoggers(); logger.info("No job specified. Here is the list of existing jobs:");
private void validateAppender(final LoggerContext loggerContext, final String expectedFilePattern) { final RollingFileAppender appender = loggerContext.getConfiguration().getAppender("fooAppender"); Assert.assertNotNull(appender); Assert.assertEquals(expectedFilePattern, appender.getFilePattern()); LogManager.getLogger("root").info("just to show it works."); } }
final File file = new File(FILE); assertTrue("Log file does not exist", file.exists()); logger.debug("This is test message number 1"); Thread.sleep(2500); final File dir = new File(DIR); break; logger.debug("Sleeping #" + i); Thread.sleep(100); // Allow time for rollover to complete final File[] files = dir.listFiles(); for (final File dirFile : files) { logger.error("Found file: " + dirFile.getPath()); final RollingFileAppender app = (RollingFileAppender) loggerContextRule.getLoggerContext().getConfiguration().getAppender("RollingFile"); final TriggeringPolicy policy = app.getManager().getTriggeringPolicy(); assertNotNull("No triggering policy", policy);
private void initializeJndi(final String location) { final URI configLocation = getConfigURI(location); if (this.name == null) { throw new IllegalStateException("A log4jContextName context parameter is required"); } LoggerContext context; final LoggerContextFactory factory = LogManager.getFactory(); if (factory instanceof Log4jContextFactory) { final ContextSelector selector = ((Log4jContextFactory) factory).getSelector(); if (selector instanceof NamedContextSelector) { this.namedContextSelector = (NamedContextSelector) selector; context = this.namedContextSelector.locateContext(this.name, this.servletContext, configLocation); ContextAnchor.THREAD_CONTEXT.set(context); if (context.isInitialized()) { context.start(); } ContextAnchor.THREAD_CONTEXT.remove(); } else { LOGGER.warn("Potential problem: Selector is not an instance of NamedContextSelector."); return; } } else { LOGGER.warn("Potential problem: LoggerContextFactory is not an instance of Log4jContextFactory."); return; } this.loggerContext = context; LOGGER.debug("Created logger context for [{}] using [{}].", this.name, context.getClass().getClassLoader()); }
/** * Validates that the code pattern we use to add an appender on the fly * works with a basic appender that is not the new OutputStream appender or * new Writer appender. */ @Test public void testUpdatePatternWithFileAppender() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); // @formatter:off final Appender appender = FileAppender.newBuilder() .withFileName("target/" + getClass().getName() + ".log") .withAppend(false) .withName("File") .withIgnoreExceptions(false) .withBufferedIo(false) .withBufferSize(4000) .setConfiguration(config) .build(); // @formatter:on appender.start(); config.addAppender(appender); ConfigurationTestUtils.updateLoggers(appender, config); LogManager.getLogger().error("FOO MSG"); } }
ctx.reconfigure(); final Configuration config = ctx.getConfiguration(); assertThat(config, instanceOf(XmlConfiguration.class)); for (final StatusListener listener : StatusLogger.getLogger().getListeners()) { config.addAppender(appender); final AppenderRef ref = AppenderRef.createAppenderRef("File", null, null); final AppenderRef[] refs = new AppenderRef[] {ref}; final LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "org.apache.logging.log4j", "true", refs, null, config, null ); loggerConfig.addAppender(appender, null, null); config.addLogger("org.apache.logging.log4j", loggerConfig); ctx.updateLoggers(); final Logger logger = ctx.getLogger(CustomConfigurationTest.class.getName()); logger.info("This is a test"); final File file = new File(LOG_FILE); assertThat(file, exists());
final File file = new File("target/test-classes/log4j2-config.xml"); assertTrue("setLastModified should have succeeded.", file.setLastModified(System.currentTimeMillis() - 120000)); ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-config.xml"); final Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator"); Configuration config = ctx.getConfiguration(); assertNotNull("No configuration", config); assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName()); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders map should not be null.", map); assertThat(map, hasSize(greaterThan(0))); TimeUnit.SECONDS.sleep(config.getWatchManager().getIntervalSeconds()+1); for (int i = 0; i < 17; ++i) { logger.debug("Test message " + i); if (is(theInstance(config)).matches(ctx.getConfiguration())) { Thread.sleep(500); final Configuration newConfig = ctx.getConfiguration(); assertThat("Configuration not reset", newConfig, is(not(theInstance(config)))); Configurator.shutdown(ctx); config = ctx.getConfiguration(); assertEquals("Unexpected Configuration.", NullConfiguration.NULL_NAME, config.getName());
@Test public void testConsecutiveReconfigure() throws Exception { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest2.xml"); final File file = new File("target", "AsyncLoggerConfigTest2.log"); assertTrue("Deleted old file before test", !file.exists() || file.delete()); final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Message before reconfig"; log.info(msg); final LoggerContext ctx = LoggerContext.getContext(false); ctx.reconfigure(); ctx.reconfigure(); final String msg2 = "Message after reconfig"; log.info(msg2); CoreLoggerContexts.stopLoggerContext(file); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(file)); final String line1 = reader.readLine(); final String line2 = reader.readLine(); reader.close(); file.delete(); assertNotNull("line1", line1); assertNotNull("line2", line2); assertTrue("line1 " + line1, line1.contains(msg)); assertTrue("line2 " + line2, line2.contains(msg2)); }
@Test public void testInitialize_Name_ClassLoader_URI() throws Exception { ctx = Configurator.initialize("Test1", null, new File("target/test-classes/log4j2-config.xml").toURI()); LogManager.getLogger("org.apache.test.TestConfigurator"); Configuration config = ctx.getConfiguration(); assertNotNull("No configuration", config); assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName()); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders map should not be null.", map); assertThat(map, hasSize(greaterThan(0))); assertThat("Wrong configuration", map, hasKey("List")); Configurator.shutdown(ctx); config = ctx.getConfiguration(); assertEquals("Unexpected Configuration.", NullConfiguration.NULL_NAME, config.getName()); }
final LoggerContext context = (LoggerContext) LogManager.getContext(false); context.start(new CompositeConfiguration(configurations)); LogManager.getLogger(LogConfigurator.class).warn("Some logging configurations have %marker but don't have %node_name. " + "We will automatically add %node_name to the pattern to ease the migration for users who customize " + "log4j2.properties but will stop this behavior in 7.0. You should manually replace `%node_name` with "
@Test public void testLogToFile() throws Exception { final Logger logger = this.ctx.getLogger(FILE_LOGGER_NAME); final long random = this.random.nextLong(); logger.debug("This is test message number {}", random); int count = 0; String line = Strings.EMPTY; try (final BufferedReader in = new BufferedReader(new FileReader(this.logFileName))) { while (in.ready()) { ++count; line = in.readLine(); } } assertThat(count, is(equalTo(1))); assertThat(line, endsWith(Long.toString(random))); }
@Test public void testRollingFileAppenderWithReconfigure() throws Exception { logger.debug("Before reconfigure"); @SuppressWarnings("resource") // managed by the rule. final LoggerContext context = loggerContextRule.getLoggerContext(); Configuration config = context.getConfiguration(); context.setConfigLocation(new URI(CONFIG)); context.reconfigure(); logger.debug("Force a rollover"); final File dir = new File(DIR); for (int i = 0; i < MAX_TRIES; ++i) { Thread.sleep(200); if (config != context.getConfiguration()) { break; } } assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertNotNull(files); assertThat(dir.listFiles().length, is(equalTo(2))); } }
final File file = new File(FILE); assertTrue("Log file does not exist", file.exists()); logger.debug("This is test message number 1, waiting for rolling"); final RollingFileAppender app = (RollingFileAppender) loggerContextRule.getLoggerContext().getConfiguration().getAppender("RollingFile"); final TriggeringPolicy policy = app.getManager().getTriggeringPolicy(); assertNotNull("No triggering policy", policy); final CronExpression expression = ((CronTriggeringPolicy) policy).getCronExpression(); assertEquals("Incorrect cron expresion", cronExpression, expression.getCronExpression()); logger.debug("Cron expression will be {}", expression.getCronExpression()); logger.debug("Adding first event {}", i);
Logger logger = LogManager.getLogger("hive.ql.metadata.Hive"); Level oldLevel = logger.getLevel(); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); loggerConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); appender.addToLogger(logger.getName(), Level.DEBUG); appender.start(); logStr.contains(expectedString)); } finally { loggerConfig.setLevel(oldLevel); ctx.updateLoggers(); appender.removeFromLogger(logger.getName());
private void addInstrumentedAppender(final MetricRegistry metrics, final Level level) { final InstrumentedAppender appender = new InstrumentedAppender(metrics, null, null, false); appender.start(); final LoggerContext context = (LoggerContext) LogManager.getContext(false); final org.apache.logging.log4j.core.config.Configuration config = context.getConfiguration(); config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).addAppender(appender, level, null); context.updateLoggers(config); }