How to override log4j properties at runtime

Apache log4j is one of several Java logging frameworks and is very popular among Java based applications as it follows the asynchronous logging mechanism which boost the over-all logging performance. log4j 2 makes use of the LMAX Disruptor, a high performance inter-thread messaging library, which reduces the need for kernel logging.
log4j can be configured through any of the following ways:

  • Properties file
  • XML file
  • Java code

Sample log4j.properties file

# Print only messages of level DEBUG or above in the package com.foo.bar
log4j.logger.com.foo.bar=INFO, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p - %m (%F:%L)%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file.
log4j.appender.R.File=./logs/application.log
log4j.appender.R.MaxFileSize=2048KB
# Keep three backup file
log4j.appender.R.MaxBackupIndex=3
# Rolling File Appender layout
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p - %m (%F:%L)%n
log4j.appender.R.append=true

In the above properties file, we have specified the log file location but in case we want to generate the log file at a variable location based on runtime input, we should override the log4j configuration with the input values.
Now, let’s say you get the log4j configuration file and log file path using java -D option which sets a system property.

java -Dapp1.log.file="/home/aaditya/apps/app1/logs/application.log" -Dapp1.log4j.properties="/home/aaditya/apps/app1/log4j.properties" -cp .:/home/aaditya/dist/appjars/app1.jar com.foo.bar.ApplicationMainClass

Now we have two new system properties:
app1.log.file will store the full path of the log-file
app1.log4j.properties will store the full path of the log4j configuration property file

Code snippet to override log4j properties at runtime

public static void main(String[] args) {
String logFilePath = System.getProperty("app1.log.file");
String log4jPropertyPath = System.getProperty("app1.log4j.properties");
modifyLog4jProperties(log4jPropertyPath, logFilePath);
}

private static void modifyLog4jProperties(String log4jPropertyPath, String logFilePath){
Properties props = new Properties();
try {
InputStream configStream = new FileInputStream(log4jPropertyPath);
props.load(configStream);
configStream.close();
} catch (IOException e) {
System.out.println("log4j configuration file not found");
}
props.setProperty("log4j.appender.R.File", logFilePath);
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);
}

The above code snippet only changes the log file path but on a similar basis we can override any of the properties specified in the log4j configuration file.
Hope it helps and thanks for reading.

Share your thoughts