I have a log4j2.xml config file in the class path. One of the appenders is a File appender, and I would like to set the target file name at run time in the Java application
I know this topic is old, but the answers did not really suit me. Here is a function which allows you to reconfigure an existing Appender at runtime:
static void updateLogger(String file_name, String appender_name, String package_name){
LoggerContext context = (LoggerContext) LogManager.getContext(false);
Configuration configuration = context.getConfiguration();
Layout extends Serializable> old_layout = configuration.getAppender(appender_name).getLayout();
//delete old appender/logger
configuration.getAppender(appender_name).stop();
configuration.removeLogger(package_name);
//create new appender/logger
LoggerConfig loggerConfig = new LoggerConfig(package_name, Level.INFO, false);
FileAppender appender = FileAppender.createAppender(file_name, "false", "false", appender_name, "true", "true", "true",
"8192", old_layout, null, "false", "", configuration);
appender.start();
loggerConfig.addAppender(appender, Level.INFO, null);
configuration.addLogger(package_name, loggerConfig);
context.updateLoggers();
}
You can specify a file name, the name of your appender and the package name which you want to log.
Example Logger:
Can be reconfigured calling like this:
updateLogger("log/api_new.log", "fileWriter_api", "my.package");