Pages

Wednesday, December 17, 2014

JEE Application with external log4j properties

JEE Application with external log4j properties

Application characteristics

- An ear with EJBs, a War and some util files
- The log4j.properties not included in the ear
- log4j.properties located a out side the server.
- Solution tested on Weblogic 12c, but should be portable to any standard JEE container.

Issue

Though it is perfectly acceptable to include the log4j.properties inside the ear/war.It comes with drawback that logging levels cannot be changed on the fly, as the levels are stated in the log4j.properties bundled with the code.  

You can overcome this drawback by removing the log4j.properties from the EAR/WAR and placing it on the server machine in location accessible by the server process. 

Here is how to get that working.

Log4j background information

The most straightforward use of log4j in your application will be to
- Include the required log4j.jar in your ear/war
- Include the log4j.properties under your resources directory for Ex.

    mockapp\mockapp-war\src\main\resources

                           
    mockapp\mockapp-ejb\src\main\resources
- Have a statement similar to the one shown below to get the logger.

 Logger logger = Logger.getLogger(MockApp.class);

Once the logger instance is obtained, print out the log statements For Ex.

logger.info("My MDB got message today using Util: " + message);

When this application is deployed and the logger.info is executed the 
log  is output to the file mentioned in the log4j.properties file.


Steps to make Log4j logging work from an external file

- You will have to leverage the org.apache.log4j.PropertyConfigurator class.
- Get the logger in the following manner:

        Logger logger = Logger.getLogger(MyClass.class);
       
        PropertyConfigurator.configureAndWatch(<Location of your log4j.properties file>);
 For Ex.
       PropertyConfigurator.configureAndWatch("C:\\log4j\\config\\mockapp\\log4j.properties");


- Remove log4j.properties files from the ear/war
- Place the properties in the desired location.
- Build the ear or war and deploy. 

Now you will notice that though you don't have a log4j.properties file in your deployed artifact (ear or war). The logs are still being created.

Calling PropertyConfigurator.configureAndWatch ensures that any changes you make to this log4j.properties file will be picked up by the server in 60 seconds.
You can change this interval by using an overloaded configureAndWatch  method that takes in the 
reload delay.


No comments:

Post a Comment