How to use Spring to load log4j.xml configuration file?

I have a simple Spring boot application that builds a jar file. I have a log4j.xml file in the src / main / resources / log4j.xml file that looks like this (main sample file from log4j docs):

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="stdout" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <!-- Pattern to output the caller file name and line number --> <param name="ConversionPattern" value="%5p [%t] (%F:%L) - %m%n"/> </layout> </appender> <appender name="R" class="org.apache.log4j.RollingFileAppender"> <param name="file" value="/tmp/logs/sample.log"/> <param name="MaxFileSize" value="100KB"/> <!-- Keep one backup file --> <param name="MaxBackupIndex" value="1"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%p %t %c - %m%n"/> </layout> </appender> <root> <priority value="debug"/> <appender-ref ref="stdout"/> <appender-ref ref="R"/> </root> </log4j:configuration> 

Logging only goes to the console, although (/tmp/logs/sample.log is never created), as the log4j.xml file is ignored.

The file appears in the root jar, which, I believe, is correct. What else do I need to do to get this registration configuration?

If that matters, the project uses Gradle, not Maven.

+6
source share
2 answers

It depends on how you customize your classpath. Is binding log4j to slf4j in your classpath (this will not be the case if you just use vanilla spring-boot-starter)? This is spring-boot-starter-log4j and sample showing how to use it (in Maven, but Gradle has the same functions).

If I were you, I would just use logback.

NB Spring Boot 1.4 does not support log4j (only log4j2). There is a sample for this in the same place.

+7
source

If we use Spring-boot and at the same time also try to use logging explicitly using log4j, Spring-boot in the built-in logging has higher priority, and therefore the log4j configuration is never read. As stated above, the best solution in this case is to exclude registration from the two Spring-boot dependencies below.

  <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> 
+1
source

All Articles