AabinGunz
AabinGunz

Reputation: 12347

how to use log4j to write a file inside my project directory?

I have a log4j properties file which is creating a file inside my tomcat>bin folder but instead can it write the log file to my project's root dir? webapps>test>___?

Here is my log4j properties file contents.

#define the console appender
log4j.appender.consoleAppender = org.apache.log4j.ConsoleAppender

# now define the layout for the appender
log4j.appender.consoleAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=%t %-5p %c{3} - %m%n

log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=/test/a.log
log4j.appender.rollingFile.MaxFileSize=10MB
log4j.appender.rollingFile.MaxBackupIndex=2
log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=%p %t %c - %m%n

# now map our console appender as a root logger, means all log messages will go to this appender
#for console printing
#log4j.rootLogger = DEBUG, consoleAppender   

#for file printing
log4j.rootLogger = DEBUG, rollingFile   

Upvotes: 9

Views: 15841

Answers (2)

Stephen C
Stephen C

Reputation: 719386

The log4j configurations understand "${catalina.home}", so ...

 log4j.appender.rollingFile.File=${catalina.home}/webapps/test/a.log

However, I don't think it is a good idea to put logs into the webapps tree because they are liable to be blown away if your webapp is redeployed.

Put them in ${catalina.home}/logs instead.

Or better still, put them in the distro-specific conventional place to put application logfiles; e.g. "/var/spool/..." or "/var/log/...".

Putting logfiles in standard places means there are less places for someone else (e.g. the guy who is the backup sysadmin when you are on holiday) to investigate if the file system fills up with old logfiles.

Upvotes: 8

Harry Joy
Harry Joy

Reputation: 59686

Try replacing this:

log4j.appender.rollingFile.File=/test/a.log

with this:

log4j.appender.rollingFile.File=../webapps/test/a.log

Note (by Stephen C) - the "../" means this solution depends on whether or not the Tomcat launch mechanism you use makes $CATALINA_HOME the current directory before the JVM that hosts Tomcat. Some do, and some don't.

Upvotes: 9

Related Questions