Hi,

 

While upgrading from 1.2.17 to 2.5, I have come across a major difference.  
Please see following code snippets.

 

Log4j1.2.17

private  static final Logger LOGGER = Logger.getLogger(TestLog.class);

public static void main(String args[])
{
    Properties p = new Properties();
    p.setProperty("log4j.debug","true");
    p.setProperty("log4j.rootLogger","info,cfg");
    p.setProperty("log4j.appender.cfg","org.apache.log4j.ConsoleAppender");
    p.setProperty("log4j.appender.cfg.layout","org.apache.log4j.PatternLayout");
    PropertyConfigurator.configure(p);
    LOGGER.info("INFO"); //logs on console
    LOGGER.warn("warn");  //logs on console
    LOGGER.error("error");  //logs on console
}

 

Log4j2 v2.5

 

private static final Logger LOGGER = LogManager.getLogger(TestLog.class);

    public static void main(String[] args)
    {
        PropertiesConfigurationFactory factory = new 
PropertiesConfigurationFactory();   // This line and the try catch below 
replace the
        Properties cfg = new Properties();
        cfg.setProperty("name", "config");
        cfg.setProperty("status", "debug");
        cfg.setProperty("appenders","console");
        cfg.setProperty("appender.console.type","Console");
        cfg.setProperty("appender.console.name","Console");
        cfg.setProperty("appender.console.layout.type","PatternLayout");
        cfg.setProperty("rootLogger.level","info");
        cfg.setProperty("rootLogger.appenderRefs","console");
        cfg.setProperty("rootLogger.appenderRef.console.ref","Console");
        try {
            ConfigurationSource configSrc = createConfigurationSource(cfg);     
           //PropertyConfigurator.configure(cfg); from log4j1.2

            Configuration conf = factory.getConfiguration(configSrc);
            System.setProperty("Log4jContextSelector", 
"org.apache.logging.log4j.core.selector.BasicContextSelector");
            LoggerContext ctx = Configurator.initialize(conf);
            ContextAnchor.THREAD_CONTEXT.set(ctx);
        }
        catch (IOException io)
        {

        }

        LOGGER.info("INFO");  // does not print
        LOGGER.warn("warn");    // does not print
        LOGGER.error("error");  //prints to console
    }

    private static ConfigurationSource createConfigurationSource(Properties 
cfg) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        cfg.store(out, null);
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        return new ConfigurationSource(in);
    }
}

 

 

So, In log4j2 , the Logger which is initialized as private static final, is not 
aware of the configurations, but in logj1.x, It is.

 

Is there any way to make log4j2 code behave as log4j1.x did?

 

Best Regards,

Tarun

Reply via email to