Custom ConfigurationFactory combined with configuration file in log4j2

I solved this problem by calling

System.setProperty("log4j.configurationFactory", CustomConfigurationFactory.class.getName());

As an alternative use this JVM start parameter:
-Dlog4j.configurationFactory=factory.CustomConfigurationFactory

instead of

ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory());

before accessing the LogManager for the first time.

-

EDIT: You can also configure this setting in the file log4j2.component.properties.

Content:

log4j.configurationFactory=factory.CustomConfigurationFactory

By doing so you can be sure this setting is applied before any logger classes are loaded and avoid the potential problems of class initialization order.

If you look for usage of org.apache.logging.log4j.util.PropertiesUtil in the Log4j2 sources you can find all settings that can be configured that way.

-

While analyzing / debugging the problem i noticed that my ConfigurationFactory was created, but not used to get the config.

Finally i found this passage in the docs, which explains it all (we probably did not call setConfigurationFactory early enough):

During initialization, Log4j 2 will search for available ConfigurationFactories and then select the one to use. The selected ConfigurationFactory creates the Configuration that Log4j will use. Here is how Log4j finds the available ConfigurationFactories:

  1. A system property named "log4j.configurationFactory" can be set with the name of the ConfigurationFactory to be used.
  2. ConfigurationFactory.setConfigurationFactory(ConfigurationFactory) can be called with the instance of the ConfigurationFactory to be used. This must be called before any other calls to Log4j.
  3. A ConfigurationFactory implementation can be added to the classpath and configured as a plugin in the "ConfigurationFactory" category. The Order annotation can be used to specify the relative priority when multiple applicable ConfigurationFactories are found.