1 minute read

Since some time I run several instances of the same application on a tomcat server. This is the poor man’s approach of multi-tenancy, I’d prefer to change the application to really support multiple tenants, but that’ll take some time.

The main problem was that everything was logged in the same log file unless I change the log4j.properties before deploying to Tomcat. I therefore wanted to change the log file location dynamically.

The very small example below shows how to change the log file for a FileAppender while using the commons logging from Apache.

import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.impl.Log4JLogger; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger;

public class LoggerTesting {

// Get a logger instance
private static Log log = LogFactory.getLog(LoggerTesting.class);

public static void main(String[] args) {

    if (log instanceof Log4JLogger) {
        // Get the actual logger implementation
    Logger logger = ((Log4JLogger) log).getLogger();

        log.debug("Debugging output");

        // Get the wanted appender defined in the log4j.properties
        Appender appender = logger.getParent().getAppender("LOGFILE");

        if (appender instanceof FileAppender) {
            FileAppender fileAppender = ((FileAppender) appender);

            // set the new file name and activate the options
            fileAppender.setFile("/tmp/test.out.log");
            fileAppender.activateOptions();
            log.info("File : " + fileAppender.getFile());
        }
    }

    log.info("Writing to changed file");

} } ```

This is straight forward since all settings from your log4j.properties are kept and you simply need to change the settings that don’t suite your needs.

Another approach was posted by Dan Moore by changing the log4j properties directly. This is IMHO very smart, but I found that posting after I’ve written the code. Nevertheless it’s got to keep that in mind, one never knows…

Tags:

Categories:

Updated: