I've been struggling a lot to get this working. Log4j2 documentation asks to define a log4j.configurationFile
system property to define a custom configuration path. I defined this property in my pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<excludes>
<exclude>**/RequestMetricsTest.java</exclude>
<exclude>**/SessionMetricsTest.java</exclude>
</excludes>
<systemProperties>
<property>
<name>log4j.configurationFile</name>
<value>src/main/resources/metrics-log4j2.xml</value>
</property>
</systemProperties>
</configuration>
</plugin>
this works perfect when I run mvn install
which executes the test cases and logs in to the file I defined in the configuration. However when I replace this built jar in my web-app it fails to log anything and keeps throwing the error about log4j2 configuration xml not found.
Question: Is there anywhere else I need to define this system property?
NOTE: I do not have web.xml
in my project.
You are specifying the system property as part of the Maven Surefire Plugin, which only applies to executed tests, that's why the configuration was not visible for your final application.
However, the configuration file is placed under /src/main/resources
, hence it will still be shipped (packaged) with the project artifact. But it does not have a standard (default) name and as such Log4j 2 needs a further parameter to point at it.
From the official F.A.Q. page:
By default, Log4j looks for a configuration file named
log4j2.xml
(notlog4j.xml
) in the classpath.
You can also specify the full path of the configuration file with this system property:
-Dlog4j.configurationFile=path/to/log4j2.xml
If you want to apply it to your web application, according to official documentation, you should add to the following to you web.xml
file
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>/metrics-log4j2.xml</param-value>
</context-param>
But since you mentioned you don't have a web.xml
file in your project (how come?) you could simply rename it to its default name (from metrics-log4j2.xml
to log4j2.xml
) and should be recognized automatically.