You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot项目中Log4j2 Layout元素CLASS_NOT_FOUND错误求助

解决Spring Boot迁移Log4j2时Layout元素CLASS_NOT_FOUND错误

问题原因分析

出现CLASS_NOT_FOUND错误,核心原因有两点:

  1. 依赖重复与版本冲突:手动添加的log4j-core、log4j-api、slf4j-api依赖,和spring-boot-starter-log4j2自带的依赖版本不一致,导致类加载时冲突,无法正确加载Layout相关类。
  2. Log4j2配置语法错误:Console appender中用<Property>子标签配置target和threshold的方式不符合规范,配置解析异常间接引发类找不到的错误。

解决方案

1. 修正依赖配置(pom.xml)

spring-boot-starter-log4j2已包含log4j-core、log4j-api、SLF4J桥接等所有必要依赖,且Spring Boot会统一管理版本,无需手动添加冗余依赖。修正后的pom.xml如下:

<dependencies>
    <!-- 排除Spring Boot默认日志依赖 -->
    <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>
    <!-- 引入Log4j2 Starter,自动管理所有相关依赖版本 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
</dependencies>

2. 修正Log4j2配置文件(log4j2.xml)

Console appender的target和threshold需直接作为属性配置,而非嵌套<Property>子标签;同时可直接使用<PatternLayout>子元素替代Layout type="PatternLayout"的写法,避免解析异常:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="console" target="System.out" threshold="INFO">
            <PatternLayout pattern="%d{HH:mm:ss,SSS} %c{1} [%p] - %m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="org.springframework" level="warn" additivity="false">
            <AppenderRef ref="console"/>
        </Logger>
        <Logger name="com.solacesystems.jcsmp" level="warn" additivity="false">
            <AppenderRef ref="console"/>
        </Logger>
        <Logger name="com.solacesystems.jms" level="warn" additivity="false">
            <AppenderRef ref="console"/>
        </Logger>
        <Root level="info">
            <AppenderRef ref="console"/>
        </Root>
    </Loggers>
</Configuration>

3. 额外排查步骤

  • 执行mvn dependency:tree命令,检查输出中是否存在logback-classic或其他非Log4j2的日志框架依赖,若有则在对应依赖中排除它们。
  • 清理项目的target编译目录,重新执行mvn clean install,避免旧的类文件或配置残留。
  • 若使用IDE开发,执行缓存清理操作(如IntelliJ的File -> Invalidate Caches...),确保IDE加载最新的依赖和配置。

内容的提问来源于stack exchange,提问作者sparker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 16:11:17