Causado por: org.apache.logging.log4j.LoggingException: log4j-slf4j-impl no puede estar presente con log4j-to-slf4j

6 minutos de lectura

Avatar de usuario de Alexei
Alexéi

En mi Bota de primavera 2 proyecto:

En build.gradle:

dependencies {
    implementation 'com.google.code.gson:gson:2.7'
    implementation 'com.h2database:h2'
    implementation 'javax.servlet:jstl:1.2'
    implementation 'org.springframework.boot:spring-boot-devtools'
    implementation('org.springframework.boot:spring-boot-starter') {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation "org.springframework.boot:spring-boot-starter-web"

    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }

    testImplementation 'org.junit.jupiter:junit-jupiter:5.5.2'
}

En src/resources/log4j2.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="Console"
              class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <!-- l, L, M - is extremely slow. It's use should be avoided unless execution
                speed is not an issue. -->
            <param name="ConversionPattern"
                   value="%p: %d{dd.MM.yyyy HH:mm:ss.SSS} %l %n    %m%n"/>
        </layout>
    </appender>

    <appender name="File"
              class="org.apache.log4j.DailyRollingFileAppender">
        <param name="Encoding" value="UTF-8"/>
        <param name="File" value="logs/trace.log"/>
        <param name="Append" value="true"/>
        <layout class="org.apache.log4j.PatternLayout">
            <!-- l, L, M - is extremely slow. It's use should be avoided unless execution
                speed is not an issue. -->
            <param name="ConversionPattern"
                   value="%p: %d{dd.MM.yyyy HH:mm:ss.SSS} %l %n    %m%n"/>
        </layout>
    </appender>

    <!-- Application Loggers -->
    <logger name="com.journaldev.spring">
        <level value="info"/>
    </logger>

    <!-- 3rdparty Loggers -->
    <logger name="org.springframework.core">
        <level value="info"/>
    </logger>

    <logger name="org.hibernate">
        <level value="info"/>
    </logger>

    <logger name="org.springframework.beans">
        <level value="info"/>
    </logger>

    <logger name="org.springframework.context">
        <level value="info"/>
    </logger>

    <logger name="org.springframework.web">
        <level value="info"/>
    </logger>

    <!-- The root category is used for all loggers unless a more specific logger
        matches. If none of the loggers are assigned a level, then all loggers inherit
        the level of the root logger which is set to DEBUG by default -->
    <root>
        <level value="ALL"/>
        <appender-ref ref="Console"/>
        <!-- <appender-ref ref="File" /> -->
    </root>

</log4j:configuration>

En mi controlador:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class CategoryController {
    private CategoryRepository categoryRepository;

    private static Logger logger = LoggerFactory.getLogger(CategoryController.class);

 @GetMapping("/categories")
    public String getCategories(Model model) {
        logger.debug("getCategories>>>>>>>>>>>>>>>>");
        model.addAttribute("categoryList", this.categoryRepository.findAll());
        return "categories/category_list";
    }
}

Pero cuando comienzo el proyecto me sale el error:

Causado por: org.apache.logging.log4j.LoggingException: log4j-slf4j-impl no puede estar presente con log4j-to-slf4j

  • Por favor lea la documentación docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…

    – Simón Martinelli

    7 de enero de 2020 a las 13:22

  • Aunque no está causando este error, el archivo de configuración que se usa es para Log4j 1.x, no para Log4j 2.

    – rgoers

    8 de enero de 2020 a las 2:43

  • Con bota de resorte 2.3.0.RELEASE+ versión, compatible con Log4j2 de forma nativa. Ver: stackoverflow.com/a/61873064/8718377

    – veben

    12 de agosto de 2021 a las 11:44


avatar de usuario de nfvp
nfvp

Según la primavera documentación (como señaló Simon), queremos excluir el módulo “spring-boot-starter-logging” de todas las bibliotecasno solo de “spring-boot-starter-web”.

configurations {
    ...
    all {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
}

…en vez de…

dependencies {
    ...
    implementation('org.springframework.boot:spring-boot-starter') {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
}

Yo mismo tuve el mismo problema y lo resolví con esta solución.

  • Recibo una advertencia de Intellij de que no se puede aplicar la exclusión a ‘java.lang.string’

    – akash bondre

    22 de febrero de 2021 a las 9:11


  • Creo que solo fue una advertencia y funcionó bien después de la compilación de gradle, gracias.

    – akash bondre

    25 de febrero de 2021 a las 9:16

  • en caso de que estés usando kotlin dsl como yo: configurations { all { exclude(group = "org.springframework.boot", module = "spring-boot-starter-logging") } }

    – jkerak

    29 de diciembre de 2021 a las 20:43


Bota de primavera 2.3.0.RELEASE versión, soporte Log4j2 de forma nativa, para registrar la configuración si está en el classpath. En este caso, simplemente puede eliminar otras dependencias de log4j.

En otro caso, si usa los iniciadores para ensamblar dependencias, debe excluir Logback y luego incluir log4j 2 en su lugar:

Puedes hacer eso con gradle:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'
}

configurations {
    all {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
}

O con Experto:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</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-log4j2</artifactId>
</dependency>

Más información sobre la documentación oficial: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-configure-log4j-for-logging

Excluí el registro de arranque de primavera de build.gradle pero el problema seguía ocurriendo. Se resolvió eliminando org.apache.logging.log4j/log4j-slf4j-impl/2.12.1 de .classpath

A partir de los registros de errores, decida qué proyecto excluir.

por ejemplo, para un mensaje de error como este: Causado por: org.apache.logging.log4j.LoggingException: log4j-slf4j-impl no puede estar presente con log4j-to-slf4j He usado la exclusión de gradle:

configuraciones.all {excluir grupo: ‘org.apache.logging.log4j’

}

Incluso después de corregir classpath, tuve el mismo problema en STS y Gradle ‘Refresh All’ lo resolvió.

Avatar de usuario de Gayathri
Gayatri

La mejor manera de resolver esto sería ejecutar dependencias de gradle e identificar de dónde proviene log4j-to-slf4j y luego excluir este módulo en build.gradle

¿Ha sido útil esta solución?