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 file

# Print only messages of level DEBUG or above in the package, stdout, R
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p - %m (%F:%L)%n
# Path and file name to store the log file.
# Keep three backup file
# Rolling File Appender layout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p - %m (%F:%L)%n

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""/home/aaditya/apps/app1/" -cp .:/home/aaditya/dist/appjars/app1.jar

Now we have two new system properties:
app1.log.file will store the full path of the log-file 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("");
modifyLog4jProperties(log4jPropertyPath, logFilePath);

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

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