0

Migrating from log4j to log4j2. Previously, the following function is called, after creating the Logger object.

public static void getLog4JSettingsFromString(String configString) throws IOException {
    Properties log4j = new java.util.Properties();
    log4j.load(new ByteArrayInputStream(configString.getBytes()));
    PropertyConfigurator.configure(log4j);
}
  • Hi Please have a look of this thread https://stackoverflow.com/questions/2288876/how-to-configure-log4j-with-a-properties-file – Raushan Kumar Jan 07 '22 at 14:56
  • Hi, that is for log4j 1.x, the code I have is for that and it works fine. What I need is a solution for the same problem on log4j 2.x. – Manoj Kommineni Jan 07 '22 at 15:16

1 Answers1

0

To configure Log4j 2.x you need to obtain a Configuration from a ConfigurationFactory:

final InputStream is = new ByteArrayInputStream(configString);
final LoggerContext context = LoggerContext.getContext(false);
final ConfigurationSource source = new ConfigurationSource(is);
final Configuration config = new PropertiesConfigurationFactory().getConfiguration(context, source);
Configurator.reconfigure(config);

There are two factories named PropertiesConfigurationFactory:

  • one that supports the Log4j 2.x configuration syntax:

    import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
    
  • one that supports (a subset of) the Log4j 1.x configuration syntax:

    import org.apache.log4j.config.PropertiesConfigurationFactory;
    

    and requires the log4j-1.2-api dependency.

Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43