Why do we need to add additional dependency for log42j in Spring Boot?

Viewed 486

Why do we need to add an additional dependency for log42j since all the transitive dependencies are already present in spring-boot-starter-web? From whatever tutorials I could read up on the internet everybody mentioned to add the dependency:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

They also mentioned excluding spring-boot-starter-logging from spring-boot-starter-web.

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

But why do we need to do this? I see all the dependencies in spring-boot-starter-log4j2 are already there in spring-boot-starter-logging.

3 Answers

The default dependency for logging is not log4j but logback. If you remove the dependency, ideally speaking you should not be able to use the log4j imports in your project. Can you check this once? The log4j dependency is only declared in the dependency-management, but you would need to include the dependency to be able to use this declared dependency.

Reference: https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/howto-logging.html

Spring by default logging is backed by Logback which is powered by Apache. So if you want to provide logging in the system you can do so using logback. Now if you are asking the question for exclusion for logback it is just for letting spring know that you are using the different logging framework.

Logging

When spring-boot-starter-logging is included:

org.springframework.boot:spring-boot-starter-logging:jar:2.4.2:compile
+- ch.qos.logback:logback-classic:jar:1.2.3:compile
|  +- ch.qos.logback:logback-core:jar:1.2.3:compile
|  \- org.slf4j:slf4j-api:jar:1.7.30:compile
+- org.apache.logging.log4j:log4j-to-slf4j:jar:2.13.3:compile
|  \- org.apache.logging.log4j:log4j-api:jar:2.13.3:compile
\- org.slf4j:jul-to-slf4j:jar:1.7.30:compile

, then log4j-core does not exist.

On the other hand, when spring-boot-starter-log4j2 is included:

org.springframework.boot:spring-boot-starter-log4j2:jar:2.4.2:compile
+- org.apache.logging.log4j:log4j-slf4j-impl:jar:2.13.3:compile
|  +- org.slf4j:slf4j-api:jar:1.7.30:compile
|  \- org.apache.logging.log4j:log4j-api:jar:2.13.3:compile
+- org.apache.logging.log4j:log4j-core:jar:2.13.3:compile
+- org.apache.logging.log4j:log4j-jul:jar:2.13.3:compile
\- org.slf4j:jul-to-slf4j:jar:1.7.30:compile

, then it exists.

Related