Before executing anything, log4j thoroughly checks the class path for log4j.xml configuration file. Let'say, by chance, if there is any log4j.xml configuration file in the library jars you referenced in your project, log4j loads that file as the configuration file and starts logging. In this context, when you are setting log file location in your FileAppender dynamically by getting the value from System properties as suggested by @Big B, it will not work since log4j had already loaded the configuration file it discovered first.
To prevent this, you can use DOMConfigurator
to inform log4j what configuration file it should load and when it should load. So, as soon as you set the system property of LogFileLocation in your program use DOMConfigurator to load intended properties file in the following way:
System.setProperty("LogFileLocation", "D:Test/Logdetails"));
DOMConfigurator.configure("log4j.xml");
By doing this way, you will load log4j.xml after you set the system property LogFileLocation in your program. (It will also override the already loaded configuration)
Inside the log4j.xml configuration, you set the file location in the param tag 'File':
<appender name="fileAppender"
class="org.apache.log4j.FileAppender">
<param name="File" value="${LogFileLocation}.log" />
<param name="Append" value="false" />
<!-- false will make the log to override the file. true will make the log to append to the file -->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{dd/MM/yyyy HH:mm:ss} %-5p %c{2}
- %m%n" />
</layout>
</appender>
To understand whatever I said better, provide -Dlog4j.debug=true
in your VM arguments and see the log of log4j execution in your console.