javavariablesdateconfiguration-fileslog4j2

date variable not resolve in log4j2.xml when using log4j 2.0 in standalone java app under osx


I'm using log4j 2 in my standalone java app. However, I'm struggling with the date variable in the log4j2.xml configuration. It's not getting resolved.

Here is my log4j2.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="File" fileName="logs/Server-${date}.log">
            <PatternLayout pattern="%d [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </appenders>
    <loggers>
        <root level="all">
            <appender-ref ref="Console"/>
            <appender-ref ref="File"/>
        </root>
    </loggers>
</configuration>

However, the log file that gets created is: Server-${date}.log

My app runs under OSX, not sure that is the cause.

Thanks guys.


Solution

  • From the Property Substitution chapter in the Log4j2 Configuration Page

    date: Inserts the current date and/or time using the specified format

    So you just have to add a date format to your property.

    ... <File name="File" fileName="logs/Server-${date:yyyy-MM-dd}.log"> ...
    

    The name of your file would be Server-2014-05-06.log.

    You can visit the SimpleDateFormat class from the Java Api to see all formatting possibilities.