13

I have log4j.xml configuration like this:

<appender name="MyAppender"class="org.apache.log4j.DailyRollingFileAppender">   
     <param name="File"     value="/logs/custom/my.log"/>
...  
 </appender>

However the root directory of my file are the same for a lot of appender. Is there a way to defined "/logs/custom/" as a variable and reused it in all of my appender.

Thanks,

Sean

Sean Nguyen
  • 12,528
  • 22
  • 74
  • 113

3 Answers3

16

UPDATE: The original answer applies to Log4j 1.x

Log4j 2.x has much richer support for properties in configuration file, see the Log4j manual about Configuration with properties.

Log4j 1.x (the original answer):

The only way to achieve something similar when you are using log4j.xml is to set a system property at startup and then reference that from your log4j.xml.

At startup, you set your system property:

java -Dlog_dir=/var/logs/custom     com.yourorg.yourapp.Main

Or set it programmatically at runtime (before initializing Log4j):

System.setProperty("log_dir", "/var/logs/custom")

Then you can reference it like this:

<appender name="MyAppender"class="org.apache.log4j.DailyRollingFileAppender">   
     <param name="File" value="${log_dir}/my.log"/>
     ...  
</appender>

Or in properties file, like this:

log4j.appender.MyAppender.File = ${log_dir}/my.log

Source: I got inspiration for this answer from Using system environment variables in log4j xml configuration.

Also, if you are running under Tomcat, you can use ${catalina.home} variable, like this:

<appender name="MyAppender"class="org.apache.log4j.DailyRollingFileAppender">   
     <param name="File" value="${catalina.home}/logs/my.log"/>
     ...  
</appender>
Community
  • 1
  • 1
Neeme Praks
  • 8,956
  • 5
  • 47
  • 47
14

It is possible in XML as well to define a variable and reuse it in the rest of the doc:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" [
  <!ENTITY logHome "/logs/folder1/folder2">
]
>

Then, refer to this variable just defined, as &logHome;

<param name="File" value="&logHome;/folder3/my.log"/>

How about that?

(I believe I learnt about XML entity references some time ago at this link: http://www.ibm.com/developerworks/xml/library/x-tipentref/index.html)

user185624
  • 141
  • 1
  • 3
6

I don't believe this is possible using XML configuration, but it is in a .properties file configuration:

mysubdir = /logs/custom
...
log4j.appender.MyAppender.File = ${mysubdir}/my.log
matt b
  • 138,234
  • 66
  • 282
  • 345
  • It is possible to use system properties in XML syntax, see the accepted answer. Not possible to define them in XML, though. – Neeme Praks Feb 05 '16 at 07:37
  • Actually, in Log4j 2.x, it is possible to define them also, in XML. https://logging.apache.org/log4j/2.x/manual/configuration.html#Configuration_with_Properties – Neeme Praks Feb 05 '16 at 07:43