tbl
tbl

Reputation: 913

How to manage log4j.properties in coding jUnit for web servlet

I'm developing web servlet and having confusion with log4j.properities, and I defined to call initialize logger in constructor.

public static Logger logger = Logger.getLogger(MyProject.class.getName());
public MyProject() {
    super();
    // TODO Auto-generated constructor stub
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = loader.getResource("log4j.properties");
    PropertyConfigurator.configure(url);
}

In general, logging file about web servlet refers to tomcat's log directory.

log4j.rootLogger=debug, R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.base}/logs/myproject.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

But, while coding jUnit for webservlet, logging file refers to improper address because ${catalina.base} is blank text. Error log is here.

[junit] log4j:ERROR setFile(null,true) call failed.
[junit] java.io.FileNotFoundException: /logs/myproject.log (No such file or directory)

So, please teach me wise management about log file. I hope stopping output log file while testing by jUnit.

Upvotes: 4

Views: 1849

Answers (1)

skaffman
skaffman

Reputation: 403611

You should maintain a separate log4j.properties for tomcat deployments and unit tests. The unit test log4j.properties is likely to be heavier on debug information, whereas the deployment version should minimise logging output to avoid being a drag on performance.

Doing this requires you to juggle the classpath properly, so that the unit test log4j.properties is picked up for unit tests, but is not packaged into the WAR. Conventionally, this goes into src/test.

Upvotes: 6

Related Questions