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); }
void register() { if (LogManager.getContext(false) instanceof LoggerContext) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); if (ctx.getConfiguration() instanceof AbstractConfiguration) { final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); final Appender appender = getSingleton(); appender.start(); config.addAppender(appender); final Logger rootLogger = LogManager.getRootLogger(); final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName()); loggerConfig.addAppender(appender, null, null); ctx.updateLoggers(); } } }
/** * Shutdown the logging system if the logging system supports it. * This is equivalent to calling {@code LogManager.shutdown(LogManager.getContext(currentContext))}. * * This call is synchronous and will block until shut down is complete. * This may include flushing pending log events over network connections. * * @param currentContext if true a default LoggerContext (may not be the LoggerContext used to create a Logger * for the calling class) will be used. * If false the LoggerContext appropriate for the caller of this method is used. For * example, in a web application if the caller is a class in WEB-INF/lib then one LoggerContext may be * used and if the caller is a class in the container's classpath then a different LoggerContext may * be used. * @since 2.6 */ public static void shutdown(final boolean currentContext) { shutdown(getContext(currentContext)); }
void deregister() { if (LogManager.getContext(false) instanceof LoggerContext) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); if (ctx.getConfiguration() instanceof AbstractConfiguration) { final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); final Appender appender = getSingleton(); appender.stop(); config.removeAppender(appender.getName()); final Logger rootLogger = LogManager.getRootLogger(); final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName()); loggerConfig.removeAppender(appender.getName()); ctx.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:");
@Test public void validateXmlSchema() throws Exception { final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml"); file.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); log.warn("Message 1"); log.info("Message 2"); log.debug("Message 3"); Configurator.shutdown(this.loggerContext); this.validateXmlSchema(file); }
Logger logger = LogManager.getLogger(LineageLogger.class); (org.apache.logging.log4j.core.Logger) logger; LoggerConfig loggerConfig = coreLogger.get(); Map<String, Appender> appenders = loggerConfig.getAppenders(); logger.debug("Debug Message Logged !!!"); logger.info("Info Message Logged !!!"); logger.error(errorString + i, new RuntimeException("part of a test"));
@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!"); } }
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."); } }
ex.getErrorMessages().stream().forEach(m -> { if (m.getCause() != null) { LOGGER.error(m.getCause().getMessage()); } else { LOGGER.error(m.getMessage()); LogManager.shutdown(); System.exit(1); LOGGER.debug("Fatal error on initialization", ex); Throwable rootCause = Throwables.getRootCause(ex); String causeMessage = rootCause.getMessage() != null ? rootCause.getMessage() : "internal error"; LogManager.shutdown(); JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage); System.exit(1);
/** * 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"); } }
ThreadContext.put("KEY", "mapvalue"); final Logger log = LogManager.getLogger("com.foo.Bar"); final LoggerContext loggerContext = LogManager.getContext(false); final String loggerContextName = loggerContext.getClass().getSimpleName(); RingBufferAdmin ring; ThreadContext.remove("count"); log.info("{} {} {} i={}", contextImpl, contextMap(), loggerContextName, Unbox.box(i)); LogManager.shutdown();
public static void main(final String[] args) { MainMapLookup.setMainArguments(args); try (final LoggerContext ctx = Configurator.initialize(MainInputArgumentsLookupTest.class.getName(), "target/test-classes/log4j-lookup-main.xml")) { LogManager.getLogger().error("this is an error message"); } }
@Override protected void log(final int runNumber) { if (runNumber == 2) { // System.out.println("Set a breakpoint here."); } final Logger logger = LogManager.getLogger("auditcsvfile"); final int val1 = 9, val2 = 11, val3 = 12; logger.info("Info Message!", val1, val2, val3); logger.info("Info Message!", val1, val2, val3); logger.info("Info Message!", val1, val2, val3); }
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 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(); assertEquals("Panic", customLevel.getLevelName()); assertEquals(17, customLevel.getIntLevel()); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!");
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)); }