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

如何在非Spring Boot项目中用Log4j开启Spring Security日志

Spring Security日志无法生效的排查与解决

核心问题定位

当前配置存在几个关键冲突点:

  1. 配置文件格式与依赖版本不兼容:使用的是Log4j 1.x格式的log4j.properties,但引入的是Log4j 2.x版本的依赖,两者配置规则不匹配。
  2. 缺少SLF4J到Log4j 2的绑定依赖:Spring Security默认通过SLF4J输出日志,没有绑定包的话,日志无法正确路由到Log4j 2。
  3. @EnableWebSecurity(debug=true)的专属日志未配置:该注解的调试日志来自org.springframework.security.web.FilterChainProxy,需单独配置日志级别才能输出。

具体解决步骤

1. 替换为Log4j 2格式的配置文件

将原log4j.properties删除,新建log4j2.xml文件(Log4j 2推荐XML格式),内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="org.hibernate" level="INFO" additivity="false">
            <AppenderRef ref="Console"/>
        </Logger>
        <Logger name="org.springframework.security" level="DEBUG" additivity="false">
            <AppenderRef ref="Console"/>
        </Logger>
        <Logger name="org.springframework.security.oauth2" level="TRACE" additivity="false">
            <AppenderRef ref="Console"/>
        </Logger>
        <!-- 开启@EnableWebSecurity(debug=true)的调试日志 -->
        <Logger name="org.springframework.security.web.FilterChainProxy" level="DEBUG" additivity="false">
            <AppenderRef ref="Console"/>
        </Logger>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

2. 补充日志绑定依赖

在pom.xml中添加SLF4J与Log4j 2的绑定包,同时排除可能存在的冲突依赖(如果是Spring Boot项目):

<!-- SLF4J 绑定 Log4j 2 -->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.19.0</version>
</dependency>

<!-- 排除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>

3. 强制指定日志配置(可选)

如果启动后日志仍不生效,添加JVM启动参数强制加载配置文件:

-Dlog4j.configurationFile=classpath:log4j2.xml

额外排查点

  • 检查项目中是否存在其他日志配置文件(如logback.xml、simplelogger.properties),这类文件会优先加载并覆盖当前配置。
  • 确认项目中没有同时引入Log4j 1.x和Log4j 2.x的依赖,可通过mvn dependency:tree命令排查依赖冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:55:28