1

I'm using log4j2 and have a rolling file configured in log4j2.xml as

<RollingFile name="a2.log" append="true"
   fileName="C:/Dev/error_log/local_error_log_app_name.log" 
   filePattern="C:/Dev/error_log/local_error_log_app_name_-%d{MM-dd-yyyy}-%i.txt.gz">

This is good for local Eclipse Development but when I deploy to a JBOSS server I'd like the path and filename to be appropriate for that file system, without having to remember to edit the log4j2.xml file before deploying.

fileName="/www/logs/error_log/error_log_app_name.log"

I've seen the following posts

How to give dynamic file name in the appender in log4j.xml

Log4J2 - assigning file appender filename at runtime

and tried fileName="$${sys:logFilename}" and fileName="${sys:logFilename}" but all that did was put a file ${sys in the Jboss bin folder `jboss-as-7.1.1.Final\bin'

Community
  • 1
  • 1
jeff
  • 3,618
  • 9
  • 48
  • 101

2 Answers2

1

Have you tried declaring a property in your config file? The log4j2 docs have an example here: http://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution

If this does not work, please raise a ticket in the log4j2 issue tracker: https://issues.apache.org/jira/browse/LOG4J2

Remko Popma
  • 35,130
  • 11
  • 92
  • 114
1

When declaring a property in log4j2.xml, use double dollar signs $$

<Properties>
    <Property name="filenameVariable">$${sys:errorLogFileName}</Property>
    <Property name="filePatternVariable">$${sys:errorLogFilePattern}</Property>
</Properties>

and reference using single dollar sign $

<RollingFile name="a2.log" append="true"
    fileName="${filename}" 
filePattern="${filePattern}">

However it is not necessary to use a property. Just reference the system property directly, again with just single dollar sign

<RollingFile name="a2.log" append="true"
    fileName="${sys:errorLogFileName}" 
filePattern="${sys:errorLogFilePattern}">

And to the answer to my actual issue how to dynamically specify log file based on whether I am running locally in Eclipse or deployed to our server, I'm using

@Singleton
@Startup
public class StartupBean {

@PostConstruct
private void startup() {

       if (File("C:/").exists()) {
         System.setProperty("errorLogFileName", "C:/path/to/error_log.txt");
         System.setProperty("errorLogFilePattern", "C:/path/to/error_log-%d{MM-dd-yyyy}-%i.txt.gz");
       } else {
         System.setProperty("errorLogFileName", "/unix/path/to/error_log.txt");
         System.setProperty("errorLogFilePattern", "/unix/path/to/error_log-%d{MM-dd-yyyy}-%i.txt.gz");
      }
}
}

Important! Without a system property set System.setProperty("whatever") the lookup in your log4j2.xml will fail and instead log4j will write to a file named as the first part of your lookup before the semicolon i.e. ${sys

Remko Popma
  • 35,130
  • 11
  • 92
  • 114
jeff
  • 3,618
  • 9
  • 48
  • 101