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

I am developing a web servlet and getting confused with log4j.properities, and I decided to call the log initialization in the 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, the web servlet log file belongs to the tomcat 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, when encoding jUnit for a webservlet, the log file refers to the wrong address, because $ {catalina.base} is empty text. The 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 how to manage log files wisely. I hope to stop the output log file during testing using jUnit.

+4
source share
1 answer

You must maintain separate log4j.properties for tomcat deployment and unit tests. unit test log4j.properties is likely to be more difficult for debugging information, while the deployment version should minimize log output to avoid performance drag and drop.

To do this, you must correctly manipulate the path so that unit test log4j.properties selected for unit tests, but not packaged in WAR. This usually goes into src/test .

+6
source

Source: https://habr.com/ru/post/1396045/


All Articles