1

Can anybody let me know if it is possible to change the fileName at runtime. I have migrated my log4j.properties to log4j2.properties successfully so far. The appenders, loggers are all being created. If I hard code the fileName then my logs are getting populated. But unfortunately the logname has to be the service name and I will know the service name only at runtime.This was possible earlier with Log4j 1.x. Earlier Call to fileAppender.setFile(logFile.getAbsolutePath()); would change the fileName during runtime. I now need to do something similar with log4J 2.4.1. I tried removing the appender,recreating it programmatically and adding the appender to the configuration but no success. Empty logfiles are being created but with the correct name. Please can anybody help me as I am just not able to figure this out. Below is my code snippet where I am trying to delete,recreate the appender.

RollingFileAppender fileAppender = (RollingFileAppender) this.config.getAppender(loggerName);
String filePattern = fileAppender.getFilePattern();
TriggeringPolicy policy = fileAppender.getTriggeringPolicy();
RolloverStrategy strategy = fileAppender.getManager().getRolloverStrategy();
PatternLayout layout = (PatternLayout) fileAppender.getLayout();
Filter filter = fileAppender.getFilter(); 
LoggerConfig lgConfig = this.config.getLogger(loggerName);
RollingFileAppender rollingFile = RollingFileAppender.createAppender(fileName, filePattern, "true", loggerName, (String)null, (String)null, (String)null, policy, strategy, layout, filter, (String)null, "false", (String)null, config);

config.removeAppender(loggerName);
config.removeLogger(loggerName);
config.addLogger(loggerName, lgConfig);
context.updateLoggers();
config.addAppender((Appender)rollingFile);

logger = LogManager.getLogger(loggerName);

"fileName" is already set by the time we reach this bit of code.

flume
  • 115
  • 1
  • 3
  • 6
  • The call to updateLoggers must come last. – Remko Popma Nov 12 '15 at 01:47
  • Tried by moving updateLoggers to the end but still empty logs. I am now checking if RoutingAppenders is the way to go for me. Although all examples of routingappenders are in log4j2.xml.I can't find anything for log4j2.properties. – flume Nov 12 '15 at 08:26
  • Also with RoutingAppenders can I have a mix of rollingfile appenders and routing appenders. In my application there are logs whose fileNames I know only during runtime(as I mentioned in my first post) and few whose fileNames I already know. So i can define a simple rollingFileAppender and logger for those. But is this possible ? – flume Nov 12 '15 at 08:29

1 Answers1

0

You should be able to create a custom Lookup to get your service name and then reference that in the configuration file.

Here is an example of how to create a custom Lookup.

Community
  • 1
  • 1
rgoers
  • 8,696
  • 1
  • 22
  • 24