Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure log4j in a unit testing environment?

Tags:

What is the best way to configure log4j for use in a unit testing environment? I prefer my unit tests to have no external dependencies, so reading the log4j configuration file is not an option. Ideally there would be 1 or 2 function calls I could make from within the unit test setup function.

like image 218
Landon Kuhn Avatar asked Jan 12 '11 20:01

Landon Kuhn


People also ask

Where should log4j properties be placed?

The file is named log4j. properties and is located in the $DGRAPH_HOME/dgraph-hdfs-agent/lib directory. The file defines the ROLLINGFILE appenders for the root logger and also sets the log level for the file. The level of the root logger is defined as INFO and attaches the ROLLINGFILE appender to it.

Where is log4j configuration file?

Sample log4j Configuration Files During Content Engine installation, two log4j sample files are placed on the system in the ContentEngine\config\samples\ folder: log4j. properties. client: A Java format file that contains client configuration settings.


2 Answers

you could put a static code block at the top of the test that does

BasicConfigurator.configure(); 

Note that the problem with this is that every time that line is executed, log4j will add an appender and you will get duplicate log statements. So if you do that in every test class, you will end up with n duplicates of every log statement.

So I recommend creating a class that is your BaseTestCase and doing that in there.

Note, having some sort of test-resources with the relevant configuration is not a bad idea...

like image 167
hvgotcodes Avatar answered Oct 05 '22 19:10

hvgotcodes


Log4j is already an external dependency. But anyway, you got your answer below (hvgotcodes), so I'll just add that you can set up log4j programatically. Basically everything you can do via config, you can do by code as well:

http://robertmaldon.blogspot.com/2007/09/programmatically-configuring-log4j-and.html

like image 44
Mike Minicki Avatar answered Oct 05 '22 20:10

Mike Minicki