Search code examples
javalogginglog4j

Adding trailing 0 in log4j (zip) file name


I am using log4j to log data. I specify the zip file using an expression like <dir_name>/$${date:yyyy-MM}/<app_name>-%d{yyyy-MM-dd}-%i.log.gz This works mostly as desired, except that I get a file name like <app_name>-2022-01-20-1.log.gz, while I want a leading zero before the 1. I am fairly certain that the number of log files will be in 2 digits, and having a leading zero helps in getting things in order while grepping across multiple files, and improves other sysadmin/debugging for the same reason.

I tried using <dir_name>/$${date:yyyy-MM}/<app_name>-%d{yyyy-MM-dd}-%ii.log.gz, but it didn't work, not that I really expected it to.

I couldn't find any documentation on what variant of %i (if any) results in a leading 0 in file name.

Any help or hints, or links to log4j documentation which covers this would be appreciated.


Solution

  • As described in the Log4J documentation for example here: https://logging.apache.org/log4j/2.x/manual/appenders.html for the filePattern field.

    The DefaultRolloverStrategy will accept both a date/time pattern compatible with SimpleDateFormat and/or a %i which represents an integer counter. The integer counter allows specifying a padding, like %3i for space-padding the counter to 3 digits or (usually more useful) %03i for zero-padding the counter to 3 digits.

    So in order for you to zero-pad your file counter with two digits you would use %02i.