I am in need of adding programmatically a file logging, with file name generated dynamically.
My code is like this:
private static final Logger LOGGER = LogManager.getLogger(Archiver.class);
public static void openLogfile(String folder) {
String dateTime = "TODO";
String fileName = folder + "upload" + dateTime + ".log";
LOGGER.info("Opening " + fileName + " for logging.");
// setting up a FileAppender dynamically...
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, null, config, null,
null, true, true, null, null);
Appender appender = FileAppender.createAppender(fileName, "false", "false", "File", "true",
"false", "false", "4000", layout, null, "false", null, config);
appender.start();
config.addAppender(appender);
AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
AppenderRef[] refs = new AppenderRef[]{ref};
LoggerConfig loggerConfig = LoggerConfig.createLogger(true, Level.DEBUG, "org.apache.logging.log4j", "", refs,
null, config, null);
loggerConfig.addAppender(appender, null, null);
config.addLogger("org.apache.logging.log4j", loggerConfig);
ctx.updateLoggers();
}
I took a look at the recipe How to add Log4J2 appenders at runtime programmatically? and to http://logging.apache.org/log4j/2.x/manual/customconfig.html#AddingToCurrent.
My problems are:
- The example on the log4j2 doc stated above would not compile, it is outdated, had to add few parameters without much idea what they are, usually I added nulls.
- The very methods used in the documentation are now deprecated;
- The file is being created but no logs appear there albeit having output on the console, and after program is quit, nothing is flushed in the file either.
Could somebody please provide a descent example with a most recent API to log4j2 to dynamically add file logging? I use org.apache.logging.log4j 2.8.1.