Search code examples
log4j2rollingfileappenderfileappender

How do I defer naming of file written by log4j2 until when the file is opened?


I am trying to have log4j2 write log files with names YYYYmmdd-HHMMSS.log, but not start writing the file until we have a good system time (>year 1986). I have an application running on a system that boots up, and takes a while to get the correct time; until that happens, the system thinks it's back in 1970, and there really is no point to writing a log file with a bum date.

Using a custom filter, I can get the FileAppender to not write any events until the system time is set. I can get the FileAppender to not open the file until the first event is passed by the custom filter (createOnDemand="true"). Using Log4J2 - assigning file appender filename at runtime, I can get the file named YYYYmmdd-HHMMSS.log, but the YYYYmmdd-HHMMSS.log in the configuration XML seems to get evaluated when log4j2 is initialized (not when the file is opened), so my file name is still 19700101-000000.log.

Is there a way to defer evaluation of the name for a log4j2 FileAppender until the file is actually opened? Alternatively, is there a sneaky way to use RollingFileAppender to do this? (I don't see a way to change the filename of the current file there, just old files)

I could do a custom appender (FileAppender/FileManager just are not all that long), but I'm trying to avoid that if possible.


Solution

  • Got an answer on the log4j2 mailing list. Thanks for Ralph Goers (one of the log4j2 developers). Use a filtered RoutingAppender to delay creation of the file appender.

    https://lists.apache.org/thread.html/rbf909f616a053f8c34733801b4977f389a31169ffcdcd3748d7873df%40%3Clog4j-user.logging.apache.org%3E