24

I'd like my web app to log into files with this path: webapp/logs/

I can set the absolute path in the log4j.properties file, but the production environment's directory structure will be different. Is there any way I could do it?

Here is how I do:

log4j.appender.f=org.apache.log4j.RollingFileAppender
log4j.appender.f.layout=org.apache.log4j.PatternLayout
log4j.appender.f.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.f.File=log.out
log4j.appender.f.MaxFileSize=100KB

This is printing logs into a file named log.log in my eclipse directory (c://eclipse). I'm using Tomcat 6.

Bob
  • 591
  • 4
  • 7
  • 13

3 Answers3

41

log4j is capable of expanding system properties, so if your production environment sets a property for the directory which you would like to place the log files in, you can reference it from the log4j.properties file.

For example, we deploy webapps on Tomcat as well. Tomcat sets up a system property named catalina.base which points to the Tomcat base directory. A log4j configuration that looks like this:

 log4j.appender.f.File = ${catalina.base}/logs/myapp.log

Will result in the myapp.log file being stored in the logs directory under the Tomcat install directory.

Samuel Edwin Ward
  • 6,526
  • 3
  • 34
  • 62
matt b
  • 138,234
  • 66
  • 282
  • 345
  • 5
    On Debian (including Ubuntu), ${catalina.home} gets you nowhere because that points at /usr/share/tomcat6 which has no link to /var/log/tomcat6. Your logfile will not be created. ${catalina.base} points at /var/lib/tomcat6 which has a link named logs to /var/log/tomcat6 and is the one to use. Hope this helps someone. – Russ Bateman Aug 05 '13 at 18:06
20

Its best to provide:
log4j.appender.f.File = ./myapp.log

. represents the current folder (usually the project root folder). This also works on different OSs. In case when you use ${catalina.home} you might not be running a web application through tomcat.

This post helped me go through the issue:
http://www.matjazcerkvenik.si/Site/Java::Log4j_Properties.html (updated link http://www.matjazcerkvenik.si/developer/java-log4j.php)

Cheers!

ohhorob
  • 11,695
  • 7
  • 41
  • 50
despot
  • 7,167
  • 9
  • 44
  • 63
  • 2
    Isn't it already the current folder by default? (i.e., prepending "./" to the path would make no difference) – golimar Mar 24 '15 at 17:34
4

log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.File=${catalina.home}/logs/myapp.log
log4j.appender.A1.DatePattern='-'yyyy-MM-dd'.log'

In this example, your current logfile will be named "myapp.log". At midnight (or when the first log entry occurs on the next day) "myapp.log" will be renamed to "myapp-yyyy-mm-dd.log" (for example,
"myapp-2010-12-21.log") and a new "myapp.log" will be created.

B. Smalley
  • 41
  • 2