简体   繁体   English

如何在编写jUnit for web servlet时管理log4j.properties

[英]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. 我正在开发web servlet并且与log4j.properities混淆了,我定义了在构造函数中调用initialize logger。

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. 通常,关于web servlet的日志文件是指tomcat的日志目录。

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. 但是,在为webservlet编写jUnit时,日志文件指的是不正确的地址,因为$ {catalina.base}是空白文本。 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. 我希望在通过jUnit测试时停止输出日志文件。

You should maintain a separate log4j.properties for tomcat deployments and unit tests. 您应该为tomcat部署和单元测试维护单独的log4j.properties 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. 单元测试log4j.properties可能在调试信息上更重,而部署版本应该最小化日志记录输出以避免拖累性能。

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. 这样做需要您正确地处理类路径,以便为单元测试选择单元测试log4j.properties ,但不将其打包到WAR中。 Conventionally, this goes into src/test . 通常,这进入src/test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM