Load Log4j2 configuration file programmatically

后端 未结 8 1514
-上瘾入骨i
-上瘾入骨i 2020-12-14 14:51

I want to load Log4j2 XML configuration file programmatically from my application.

Tried this:

ConfigurationSource source = new ConfigurationSource()         


        
8条回答
  •  青春惊慌失措
    2020-12-14 15:28

    Below worked for me, Log4j2 with SLF4J wrapper:

    Solution 1:

    public class MyClass {
    
        static {
            try {
                InputStream inputStream = new FileInputStream("C:/path/to/log4j2.xml");
                ConfigurationSource source = new ConfigurationSource(inputStream);
                Configurator.initialize(null, source);
            } catch (Exception ex) {
                // Handle here
            }
        }
    
        private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class); // LogManager if not using SLF4J
    
        public void doSomething() {
            LOGGER.info(...)
        }
    
    }
    

    Solution 2:

    static {
        File log4j2File = new File("C:/path/to/log4j2.xml");
        System.setProperty("log4j2.configurationFile", log4j2File.toURI().toString());
    }
    

    Need toURI() to follow File URI Scheme format, else it throws MalformedURLException.

    Sources:

    • Proper format for log4j2.xml RollingFile configuration
    • https://github.com/jprante/elasticsearch-jdbc/issues/562
    • https://www.codeproject.com/Questions/190269/MalformedURLException-unknown-protocol-c-How-to-ha
    • https://coderanch.com/t/633544/open-source/java-net-MalformedURLException-initialize-log

提交回复
热议问题