In the below main class, we are first giving the application properties file (path) used by the application as an argument.
In the properties file, we have the path of the log file. So, we can change the log file location at runtime.
In addition to this, by this way, we can also change the log level, pattern layout, appender type, …
public class ApplicationStarter { private static final Logger log = Logger.getLogger(ApplicationStarter.class); private static String propFileLoc; public static void main(String[] args) { ApplicationStarter app = new ApplicationStarter(); if (args.length == 0) { System.err.println("Argument error. Please check properties file location in startup script."); return; } else if (args.length > 1) { System.err.println("Argument error. Please check the arguments in startup script."); return; } else { propFileLoc = args[0]; } try { Utils.loadProperties(propFileLoc); System.out.println("Properties loaded successfully"); } catch (Exception e1) { System.err.println("Error while loading properties..."); e1.printStackTrace(); return; } // set log file location app.updateLog4jConfiguration( String.valueOf( Utils.props.get("logFile") )); log.error("TEst"); ... } private void updateLog4jConfiguration(String logFile) { Properties props = new Properties(); try { InputStream configStream = getClass().getResourceAsStream( "/log4j.properties"); props.load(configStream); configStream.close(); } catch (IOException e) { System.out.println("Error: Cannot laod configuration file "); } props.setProperty("log4j.appender.FILE.file", logFile); LogManager.resetConfiguration(); PropertyConfigurator.configure(props); } } application.properties : logFile=D:/temp/applicationLog.log log4j.properties: log4j.rootLogger=INFO, FILE log4j.appender.FILE=org.apache.log4j.FileAppender log4j.appender.FILE.file=jms-alarms.log log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
In this example, we changed only log file location but you can even change pattern, layout, log level and any of the values in log4j.properties file.
The main trick here is to put following line in your running code to reset Lo4j its properties with the new values.
LogManager.resetConfiguration();
great….
i have not tested this code…. but i think this will solve my problem…
a big releif…
thanks