4

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
tbl
  • 823
  • 1
  • 8
  • 11
  • See also http://stackoverflow.com/questions/24231773/specifying-a-custom-log4j-properties-file-for-all-of-junit-tests-run-from-eclips – Raedwald Jan 23 '15 at 20:04

1 Answers1

6

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • "minimise logging output to avoid being a drag on performance": and so the important messages (errors, warnings) are not swamped by unimportant messages. – Raedwald Jul 05 '13 at 09:41