I was able to get the following code to work.  This code was placed in a method 
in a class that was in the same package as the log4j2.xml file.  I call this 
method in the main entry point of my application before getting any loggers.  I 
had to do a google search to find out about the Configurator.  Maybe it is in 
the documentation on the website but I didn't see it mentioned anywhere.

        InputStream is = MyLogFactory.class.getResourceAsStream("log4j2.xml");
        ConfigurationSource source = new ConfigurationSource(is);
        Configurator.initialize(MyLogFactory.class.getClassLoader(), source);

Thx Blaine

From: Blaine Bergeson (bbergeson)
Sent: Thursday, January 22, 2015 9:38 AM
To: [email protected]
Subject: Programmatically loading of the configuration file

I can't seem to load a configuration file?  The reason I am doing this is 
because I have my configuration file in a package that is not on the default 
classpath.  Adding the package to the classpath is not straight forward.  Also, 
I don't want to add a system property or environment variable because we will 
be reusing this package throughout all of our projects.  So the idea is that 
this package will just be pulled into a project and it will contain the 
configuration file along with a class that will add the correct items to the 
context map and will load the configuration file.  The developer should just be 
able to include the package and they are off and running.

I am using the following code to load the config file which resides in the same 
package as the class that this method is part of, but it is not working.  As I 
step through the code I can see that inside ConfigurationSource the stream is 
loaded correctly with the contents of my file so I know that it found it but 
when the getContext line is executed I get an error saying that it could not 
locate a configuration file.  What am I missing?

        try {
            InputStream is = 
MyLogFactory.class.getResourceAsStream("log4j2.xml");
            ConfigurationSource source = new ConfigurationSource(is);
            Configuration config = 
XmlConfigurationFactory.getInstance().getConfiguration(source);
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            ctx.stop();
            ctx.start(config);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }

Thx Blaine

Reply via email to