0

I am using log4j for logging activities in my application.I want to take the log path from data base. now I need to configure my log4j properties dynamically.

can we do it on the fly we change the log4h logging path..

Please suggest.

Thanks

Pedantic
  • 1,368
  • 10
  • 39
  • 70
  • See http://stackoverflow.com/questions/4598702/dynamically-changing-log4j-log-level for some approaches to changing the log config dynamically. – DNA Sep 28 '11 at 12:33

3 Answers3

2

You should create a class what loads at the startup and configurate the log4j. Here is a code what I used in a JavaEE project, what loads the configuration file from an outer directory:

public class InitListener implements ServletContextListener {

public InitListener() {
}

public void contextInitialized(ServletContextEvent sce) {
    try {
        File    file  = null;
        file = new File(System.getProperty("catalina.base") + "/conf/query-log4j.xml");
        DOMConfigurator.configure(file.toURL());
        System.out.println("Log4J successfully configured!");
    } catch(Exception e) {
        System.out.println("There was an error when initialize the Log4J config!");
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

public void contextDestroyed(ServletContextEvent sce) {
}

}

Csujo
  • 507
  • 2
  • 6
  • Hi,Thannks for the reply, my actual problem is how to change the log path on fly. i can not hard code the path in environment. – Pedantic Sep 29 '11 at 12:29
1

If you were using MentaLog, all you have to do was that:

yourLogger.setFilename("newfilenamehere.log");

Your log would be automatically re-opened with the new name. In my personal opinion, programmatic configuration is the way to go over XML and/or annotations. It provides unmatched flexibility and easy of use.

JohnPristine
  • 3,485
  • 5
  • 30
  • 49
0

Create seperate properties file to hold Specific Enviroment related settings example:

**uatLog4j.properties**
#######################
UAT Settings
#######################

{Add your Settings here}

And another for sy production enviroment.

**productionLog4j.properties**
########################
PRODUCTION settings
########################

{Add your Settings here}

And then using say the IP Address or the Server Name to determine the deployed platform, pass the path from the database to the required enviroment properties file as required.

Alternatively you can use LogManager to retreive Logger instances or to operate on the current LoggerRepository. See Javadoc and a RepositorySelecter example.

NOTE: You can achieve the same using XML.

Bitmap
  • 12,402
  • 16
  • 64
  • 91