Tuesday, July 24, 2007

How to capture logging output in unit tests

When writing unit tests for java, its extremely valuable to view the log statements produced by your unit tests and java code. The following is a brief introduction on how to configure maven1 and maven2 projects to capture logs.

Maven1
The maven-test-plugin is used for running unit tests in maven1 projects. It is best to configure this plugin at a global level in your build.properties file located under your $USER_HOME.

First add the following to your $USER_HOME/build.properties file:

maven.junit.sysproperties=log4j.configuration
log4j.configuration=file:/c:/Documents and Settings/jlorenzen/log4j.properties

Second add a log4j.properties file under your $USER_HOME directory. Mostly likely this will include a ConsoleAppender. By using a ConsoleAppender the maven-test-plugin will capture the logs and write them to the console. However its cleaner if you set the property maven.junit.usefile=true in your build.properties file. This will put all your logs in the .txt test report file.

Maven2
Unfortunately things are a bit different for maven2 projects. You no longer use the maven-test-plugin but rather the maven-surefire-plugin. The following example will use java logging.

To get started open up your project's parent pom.xml and add the following for the maven-surefire-plugin.

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemProperties>
<property>
<name>java.util.logging.config.file</name>
<value>${logging.location}</value>
</property>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
Next you need to define the value for the variable ${logging.location}. You do this in your settings.xml file which is located under $USER_HOME/.m2. If you do not already have a settings.xml file you can get an empty one under your maven2 install in the directory $M2_HOME/conf. To define the value for ${logging.location} create a profile in your $USER_HOME/.m2/settings.xml file like the following:
<profiles>
<profile>
<id>configure.logging.location.profile</id>
<properties>
<logging.location>${user.home}/.m2/logging.properties</logging.location>
</properties>
</profile>
</profiles>

Next you need to activate the profile by adding the following in your settings.xml:

<activeprofiles>
<activeprofile>configure.logging.location.profile</activeprofile>
</activeprofiles>
Since the surefire plugin does not put log statements in the output file when using the redirectTestOutputToFile, viewing the log statements in the console can be a bit overwhelming. To make this easier consider using the test single goal: mvn -Dtest=ClassName test

2 comments:

Guy said...

It might have been changed in a newer version, but with Maven 2.2.0, it must be systemProperties, capital P.

Anonymous said...

groupid and artifactid should have I capitalized. I think the XML in the example is lowercased by accident.