tholu tholu - 7 months ago 50
Java Question

log4j.properties ignored when using mvn exec:java

I'm using

mvn exec:java -Dexec.mainClass=my.Class
to run on the command-line. While the program is running, I have some debug output, which I would like to log.

I use
private static Logger logger = LoggerFactory.getLogger("mylogger");
to initialize the logger. I have configured it like this in log4j.properties:

log4j.appender.mylogger=org.apache.log4j.DailyRollingFileAppender
log4j.appender.mylogger.Threshold=DEBUG
log4j.appender.mylogger.File=logs/mylogger.log
log4j.appender.mylogger.DatePattern=.yyyy-MM
log4j.appender.mylogger.layout=org.apache.log4j.PatternLayout
log4j.appender.mylogger.layout.ConversionPattern=%d{ISO8601} [%5p] %C{1}:%L - %m%n
log4j.additivity.mylogger=false


However,
logger
has the class
org.slf4j.impl.JDK14LoggerAdapter
and seems to ignore all settings in
log4j.properties
- it is logging to STDERR with localized warnings and infos.

My relevant maven dependencies:

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>


How do I get my custom configured logger when using
mvn exec:java
? My log4j.properties configuration works fine when running the rest of the Spring application with Jetty.

Answer

JDK14LoggerAdapter is part of slf4j-jdk14-1.7.21.jar. So my guess is that your classpath contains this jar.

As mvn exec:java and jetty use different class loaders you are only lucky with jetty that he preferred the slf4j-log4j12 over the jdk14 binding.

Also, make sure exec:java includePluginDependencies is not set to true (it's false by default) http://www.mojohaus.org/exec-maven-plugin/java-mojo.html.

In case that after removing the offensive jar your command-line will still want pick the log4.properties file. i.e. typing the following error to the console :

log4j:WARN No appenders could be found for logger (dao.hsqlmanager).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

You can provide the path to the properties file passing the system property log4j.configuration to mvn exec:java

How to pass systemProperties when invoking exec:java plugin in maven?