org.apache.logging.log4j.core.config.ConfigurationFactory Java Examples

The following examples show how to use org.apache.logging.log4j.core.config.ConfigurationFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoggerContextAdmin.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void setConfigText(final String configText, final String charsetName) {
    LOGGER.debug("---------");
    LOGGER.debug("Remote request to reconfigure from config text.");

    try {
        final InputStream in = new ByteArrayInputStream(configText.getBytes(charsetName));
        final ConfigurationSource source = new ConfigurationSource(in);
        final Configuration updated = ConfigurationFactory.getInstance().getConfiguration(loggerContext, source);
        loggerContext.start(updated);
        LOGGER.debug("Completed remote request to reconfigure from config text.");
    } catch (final Exception ex) {
        final String msg = "Could not reconfigure from config text";
        LOGGER.error(msg, ex);
        throw new IllegalArgumentException(msg, ex);
    }
}
 
Example #2
Source File: LoggerContext.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Reconfigures the context.
 */
private void reconfigure(final URI configURI) {
    Object externalContext = externalMap.get(EXTERNAL_CONTEXT_KEY);
    final ClassLoader cl = ClassLoader.class.isInstance(externalContext) ? (ClassLoader) externalContext : null;
    LOGGER.debug("Reconfiguration started for context[name={}] at URI {} ({}) with optional ClassLoader: {}",
            contextName, configURI, this, cl);
    final Configuration instance = ConfigurationFactory.getInstance().getConfiguration(this, contextName, configURI, cl);
    if (instance == null) {
        LOGGER.error("Reconfiguration failed: No configuration found for '{}' at '{}' in '{}'", contextName, configURI, cl);
    } else {
        setConfiguration(instance);
        /*
         * instance.start(); Configuration old = setConfiguration(instance); updateLoggers(); if (old != null) {
         * old.stop(); }
         */
        final String location = configuration == null ? "?" : String.valueOf(configuration.getConfigurationSource());
        LOGGER.debug("Reconfiguration complete for context[name={}] at URI {} ({}) with optional ClassLoader: {}",
                contextName, location, this, cl);
    }
}
 
Example #3
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: FlumeEmbeddedAgentTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

    final File file = new File("target/file-channel");
    deleteFiles(file);

    /*
    * Clear out all other appenders associated with this logger to ensure we're
    * only hitting the Avro appender.
    */
    final int primaryPort = AvailablePortFinder.getNextAvailable();
    final int altPort = AvailablePortFinder.getNextAvailable();
    System.setProperty("primaryPort", Integer.toString(primaryPort));
    System.setProperty("alternatePort", Integer.toString(altPort));
    primary = new EventCollector(primaryPort);
    alternate = new EventCollector(altPort);
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
    ctx = LoggerContext.getContext(false);
    ctx.reconfigure();
}
 
Example #6
Source File: FlumeEmbeddedAgentTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@After
public void teardown() throws Exception {
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    ctx.reconfigure();
    primary.stop();
    alternate.stop();
    final File file = new File("target/file-channel");
    deleteFiles(file);
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    final Set<ObjectName> names = server.queryNames(new ObjectName("org.apache.flume.*:*"), null);
    for (final ObjectName name : names) {
        try {
            server.unregisterMBean(name);
        } catch (final Exception ex) {
            System.out.println("Unable to unregister " + name.toString());
        }
    }
}
 
Example #7
Source File: FlumePersistentPerf.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

    final File file = new File("target/persistent");
    deleteFiles(file);

    /*
    * Clear out all other appenders associated with this logger to ensure we're
    * only hitting the Avro appender.
    */
    final int primaryPort = AvailablePortFinder.getNextAvailable();
    final int altPort = AvailablePortFinder.getNextAvailable();
    System.setProperty("primaryPort", Integer.toString(primaryPort));
    System.setProperty("alternatePort", Integer.toString(altPort));
    primary = new EventCollector(primaryPort);
    alternate = new EventCollector(altPort);
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
    ctx = LoggerContext.getContext(false);
    ctx.reconfigure();
}
 
Example #8
Source File: JdbcAppenderBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Setup
public void setup() throws Exception {
    connectionHSQLDB = getConnectionHSQLDB();
    connectionH2 = getConnectionH2();
    createTable(connectionHSQLDB, toCreateTableSqlStringHQLDB("fmLogEntry"));
    createTable(connectionH2, toCreateTableSqlStringH2("fmLogEntry"));

    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j2-jdbc-appender.xml");
    final LoggerContext context = LoggerContext.getContext(false);
    if (context.getConfiguration() instanceof DefaultConfiguration) {
        context.reconfigure();
    }
    StatusLogger.getLogger().reset();
    loggerH2 = LogManager.getLogger("H2Logger");
    loggerHSQLDB = LogManager.getLogger("HSQLDBLogger");
}
 
Example #9
Source File: FlumePersistentPerf.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@After
public void teardown() throws Exception {
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    ctx.reconfigure();
    primary.stop();
    alternate.stop();
    final File file = new File("target/file-channel");
    deleteFiles(file);
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    final Set<ObjectName> names = server.queryNames(new ObjectName("org.apache.flume.*:*"), null);
    for (final ObjectName name : names) {
        try {
            server.unregisterMBean(name);
        } catch (final Exception ex) {
            System.out.println("Unable to unregister " + name.toString());
        }
    }
}
 
Example #10
Source File: FlumeEmbeddedAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@After
public void teardown() throws Exception {
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    ctx.reconfigure();
    primary.stop();
    alternate.stop();
    final File file = new File("target/file-channel");
    deleteFiles(file);
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    final Set<ObjectName> names = server.queryNames(new ObjectName("org.apache.flume.*:*"), null);
    for (final ObjectName name : names) {
        try {
            server.unregisterMBean(name);
        } catch (final Exception ex) {
            System.out.println("Unable to unregister " + name.toString());
        }
    }
}
 
Example #11
Source File: FlumePersistentAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

    final File file = new File("target/persistent");
    deleteFiles(file);

    /*
    * Clear out all other appenders associated with this logger to ensure we're
    * only hitting the Avro appender.
    */
    final int primaryPort = AvailablePortFinder.getNextAvailable();
    final int altPort = AvailablePortFinder.getNextAvailable();
    System.setProperty("primaryPort", Integer.toString(primaryPort));
    System.setProperty("alternatePort", Integer.toString(altPort));
    primary = new EventCollector(primaryPort);
    alternate = new EventCollector(altPort);
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
    ctx = LoggerContext.getContext(false);
    ctx.reconfigure();
}
 
Example #12
Source File: AbstractJpaAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public void tearDown() throws SQLException {
    final LoggerContext context = LoggerContext.getContext(false);
    try {
        String appenderName = "databaseAppender";
        final Appender appender = context.getConfiguration().getAppender(appenderName);
        assertNotNull("The appender '" + appenderName + "' should not be null.", appender);
        assertTrue("The appender should be a JpaAppender.", appender instanceof JpaAppender);
        ((JpaAppender) appender).getManager().close();
    } finally {
        System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
        PropertiesUtil.getProperties().reload();
        context.reconfigure();
        StatusLogger.getLogger().reset();

        try (Statement statement = this.connection.createStatement();) {
            statement.execute("SHUTDOWN");
        }

        this.connection.close();
    }
}
 
Example #13
Source File: QueueFullAsyncAppenderTest2.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    //FORMAT_MESSAGES_IN_BACKGROUND
    System.setProperty("log4j.format.msg.async", "true");

    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "log4j2-queueFullAsyncAppender.xml");
}
 
Example #14
Source File: RollingAppenderUncompressedTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void cleanupClass() {
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    final LoggerContext ctx = LoggerContext.getContext();
    ctx.reconfigure();
    StatusLogger.getLogger().reset();
}
 
Example #15
Source File: AsyncLoggerTestNanoTime.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "NanoTimeToFileTest.xml");
}
 
Example #16
Source File: XmlConfigurationPropsTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithProps() {
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
    System.setProperty("log4j.level", "warn");
    System.setProperty("log.level", "warn");
    try {
        final LoggerContext ctx = LoggerContext.getContext();
        ctx.reconfigure();
        final Configuration config = ctx.getConfiguration();
        assertTrue("Configuration is not an XmlConfiguration", config instanceof XmlConfiguration);
    } finally {
        System.clearProperty("log4j.level");
        System.clearProperty("log.level");
    }
}
 
Example #17
Source File: QueueFullAsyncLoggerTest2.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    //FORMAT_MESSAGES_IN_BACKGROUND
    System.setProperty("log4j.format.msg.async", "true");

    System.setProperty("AsyncLogger.RingBufferSize", "128"); // minimum ringbuffer size
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "log4j2-queueFull.xml");
}
 
Example #18
Source File: Rfc5424LayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() {
    StatusLogger.getLogger().setLevel(Level.OFF);
    ConfigurationFactory.setConfigurationFactory(cf);
    final LoggerContext ctx = LoggerContext.getContext();
    ctx.reconfigure();
}
 
Example #19
Source File: PerformanceComparison.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void cleanupClass() {
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    System.clearProperty(LOGBACK_CONF);
    System.clearProperty(LOG4J_CONF);
    new File("target/testlog4j.log").deleteOnExit();
    new File("target/testlog4j2.log").deleteOnExit();
    new File("target/testlogback.log").deleteOnExit();
}
 
Example #20
Source File: JsonLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() {
    ThreadContext.clearAll();
    ConfigurationFactory.setConfigurationFactory(cf);
    final LoggerContext ctx = LoggerContext.getContext();
    ctx.reconfigure();
}
 
Example #21
Source File: QueueFullAsyncLoggerConfigTest2.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    //FORMAT_MESSAGES_IN_BACKGROUND
    System.setProperty("log4j.format.msg.async", "true");

    System.setProperty("AsyncLoggerConfig.RingBufferSize", "128"); // minimum ringbuffer size
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "log4j2-queueFullAsyncLoggerConfig.xml");
}
 
Example #22
Source File: XmlConfigurationPropsTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void cleanupClass() {
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    final LoggerContext ctx = LoggerContext.getContext();
    ctx.reconfigure();
    StatusLogger.getLogger().reset();
}
 
Example #23
Source File: EventParameterMemoryLeakTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty("log4j2.enable.threadlocals", "true");
    System.setProperty("log4j2.enable.direct.encoders", "true");
    System.setProperty("log4j2.is.webapp", "false");
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "EventParameterMemoryLeakTest.xml");
}
 
Example #24
Source File: UrlConnectionFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static HttpURLConnection createConnection(URL url, long lastModifiedMillis, SslConfiguration sslConfiguration)
    throws IOException {
    final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    AuthorizationProvider provider = ConfigurationFactory.getAuthorizationProvider();
    if (provider != null) {
        provider.addAuthorization(urlConnection);
    }
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setRequestMethod("GET");
    if (connectTimeoutMillis > 0) {
        urlConnection.setConnectTimeout(connectTimeoutMillis);
    }
    if (readTimeoutMillis > 0) {
        urlConnection.setReadTimeout(readTimeoutMillis);
    }
    String[] fileParts = url.getFile().split("\\.");
    String type = fileParts[fileParts.length - 1].trim();
    String contentType = isXml(type) ? XML : isJson(type) ? JSON : isProperties(type) ? PROPERTIES : TEXT;
    urlConnection.setRequestProperty("Content-Type", contentType);
    if (lastModifiedMillis > 0) {
        urlConnection.setIfModifiedSince(lastModifiedMillis);
    }
    if (url.getProtocol().equals(HTTPS) && sslConfiguration != null) {
        ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslConfiguration.getSslSocketFactory());
        if (!sslConfiguration.isVerifyHostName()) {
            ((HttpsURLConnection) urlConnection).setHostnameVerifier(LaxHostnameVerifier.INSTANCE);
        }
    }
    return urlConnection;
}
 
Example #25
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #26
Source File: AsyncLoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
            AsyncLoggerContextSelector.class.getName());
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            "AsyncLoggerTest.xml");
}
 
Example #27
Source File: AbstractAsyncThreadContextTestBase.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void afterClass() {
    System.clearProperty("AsyncLogger.RingBufferSize");
    System.clearProperty("AsyncLoggerConfig.RingBufferSize");
    System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR);
    System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
    System.clearProperty("log4j2.garbagefree.threadContextMap");
    System.clearProperty("log4j2.is.webapp");
    System.clearProperty("log4j2.threadContextMap");
}
 
Example #28
Source File: AsyncLoggerConfigTest2.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #29
Source File: AsyncLoggerConfigWithAsyncEnabledTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    System.setProperty("log4j2.is.webapp", "false");
    System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getCanonicalName());
    // Reuse the configuration from AsyncLoggerConfigTest4
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest4.xml");
}
 
Example #30
Source File: AbstractJpaAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public void setUp(final String configFileName) throws SQLException {
    this.connection = this.setUpConnection();

    final String resource = "org/apache/logging/log4j/jpa/appender/" + configFileName;
    assertNotNull(getClass().getClassLoader().getResource(resource));
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            resource);
    PropertiesUtil.getProperties().reload();
    final LoggerContext context = LoggerContext.getContext(false);
    if (context.getConfiguration() instanceof DefaultConfiguration) {
        context.reconfigure();
    }
    StatusLogger.getLogger().reset();
}