Apache Log4j不读取properties配置文件 无法按天生成日志求助
问题核心原因
你遇到的配置不生效问题主要来自2个版本适配错误:
- 你代码中导入的
org.apache.logging.log4j属于Log4j 2.x版本,但你编写的log4j.properties是Log4j 1.x版本的专属配置文件,Log4j 2.x完全不识别该格式的配置文件,所以第一份配置没有任何效果 application.properties中的logging.*配置是Spring Boot框架的专属配置项,默认适配的是Spring Boot内置的Logback日志实现,如果你没有主动替换日志实现、或是你的项目本身不是Spring Boot项目,这部分配置也不会生效
可选解决方案
方案1:继续使用Log4j2作为日志实现
第一步:调整依赖(Spring Boot项目适用,普通Java项目可跳过)
先排除Spring Boot默认携带的Logback依赖,再引入Log4j2的适配依赖,pom.xml参考配置如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 排除默认Logback依赖 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- 引入Log4j2依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
第二步:修改Log4j2配置文件
将原log4j.properties重命名为log4j2.properties,替换为符合Log4j2规范的按天滚动配置,参考如下:
status = error name = PropertiesConfig appender.rolling.type = RollingFile appender.rolling.name = RollingFile appender.rolling.fileName = app.log appender.rolling.filePattern = app.%d{yyyy-MM-dd}.log appender.rolling.layout.type = PatternLayout appender.rolling.layout.pattern = [%p] %d %c %M - %m%n appender.rolling.policies.type = Policies appender.rolling.policies.time.type = TimeBasedTriggeringPolicy appender.rolling.policies.time.interval = 1 appender.rolling.policies.time.modulate = true rootLogger.level = debug rootLogger.appenderRef.rolling.ref = RollingFile
把配置文件放在src/main/resources根目录下即可生效。
方案2:使用Spring Boot默认Logback实现(无需额外改依赖)
不需要单独写日志框架配置文件,直接完善application.properties的配置即可实现按天滚动:
logging.file.name=application.log # 配置按天滚动的文件名规则 logging.logback.rollingpolicy.file-name-pattern=application-%d{yyyy-MM-dd}.%i.log # 单文件超过100MB时自动切分 logging.logback.rollingpolicy.max-file-size=100MB # 最多保留30天日志 logging.logback.rollingpolicy.max-history=30
内容的提问来源于stack exchange,提问作者Thomson Mathew
相关产品推荐
相关产品推荐

