log4j in maven tests

If you want to specify log4j configuration when running tests via Maven, you can do so by updating the Maven surefire plugin configuration to point to a specific log4j configuration file. For log4j v2 the appropriate parameter is called log4j.configuration. e.g.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemProperties>
            <property>    
                <name>log4j.configurationFile</name>
                <value>src/test/resources/log4j2-module-name.xml</value>
            </property>
        </systemProperties>
    </configuration>
</plugin>

You can see from the snippet that, since the tests run from the top level of the current module, the path to the file needs to include the path to the test resources folder. Alternatively, the log4j.configurationFile name does support a fully qualified URL in the form file://. The other thing you will notice is that I haven’t used the default name of “log4j2.xml” as the file name. This is because in a large maven project it can be confusing to have many files with the same name, so I prefer to put the module name into the file name to make things clearer.

This entry was posted in Java, Maven and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

503,793 Spambots Blocked by Simple Comments

HTML tags are not allowed.