'Roll Logs Into Specific Directory Log4j2

Goal: Have Log4j2:

  1. Create the root "logs" directory if it doesn't exist.
  2. Create an "archive" directory if it doesn't exist so RollingFile appender can save the rolled logs.

Expected Result:

..\logs\MyLog.log
..\logs\archive\MyLog_2022-03-03_1.log
..\logs\archive\MyLog_2022-03-03_2.log
..\logs\archive\MyLog_2022-03-03_3.log
.
.
..\logs\archive\MyLog_2022-03-03_20.log

I'm expecting the creation of "logs" & "archive" directories in case they aren't there on start-up/1st roll.

Actual Results:

Regarding the "logs" directory:

  • if the "logs" directory doesn't exist prior to start-up then system continues running without logging anything or creating the directory.
  • if the "logs" directory exists prior to start-up then it saves the main log file to it.

Regarding the "archive" directory for rolling logs:

  • if the "archive" directory doesn't exist prior to start-up then it is created, the system crashes and an exception is thrown.
  • if the "logs" directory exists prior to start-up then the system crashes and an exception is thrown.

What I have tried:

  1. Replacing the properties with their actual hard-coded values.
  2. Replacing the path with "./" at the beginning.
  3. Replacing the path with "../" at the beginning.
  4. Replacing the beginning of the path with various possible Lookups from Log4j2's documentation.
  5. Hard-coding the full-path, which worked but is not an option to use as it will change according to the customer's installation location.

Configuration:

<Properties>
    <Property name="log.dir">logs</Property>
    <Property name="log.file">MyLog</Property>
    <Property name="pattern">%d %-5p [%t] %c{2}:%L - %m%n</Property>
</Properties>

<RollingFile name="MainLog" fileName="${log.dir}/${log.file}.log" filePattern="${log.dir}/archive/${log.file}_%d{MM-dd-yyyy}_%i.log.gz">
    <PatternLayout pattern="${pattern}" />
    <Policies>
        <SizeBasedTriggeringPolicy size="20 MB" />
    </Policies>
    <DefaultRolloverStrategy max="20" />
</RollingFile>

Research:

I've tried various Google searches and looked into many Stackoverflow questions, I will not be listing them here as they do not include any actual relevant data.
Weirdly enough, I wasn't able to find any similar question.

What am I missing?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source