springboot + log4j2

本文详述了如何在SpringBoot项目中替换默认的logback日志框架,集成更高效的Log4j2,包括配置文件调整、日志级别设置、多文件滚动策略及彩色输出配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

log4j2是对log4j的一种颠覆式变化,添加多线程下的无锁写入,比logback速度还快。废弃了之前的properties方式,用xml或json来代替。

springboot集成需要先移除默认的logback依赖。

在spring-boot-start和spring-boot-start-test中添加以下内容,移除logback

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

再添加:

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

因log4j2和logback现在统一使用SLF4j作为统一API因此如果lombok的话,则不用做任何修改。

springboot默认支持log4j的名字是  log4j2-spring.xml

spring的application.properties中添加以下内容。

logging.config=classpath:log4j2-spring.xml
spring.output.ansi.enabled=ALWAYS

同时创建log4j2-spring.xml文件,即可输出log4j内容。

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF" packages="cn.com.testproject">
    <appenders>
        <Console name="console">
            <PatternLayout pattern="%highlight{[%p] %-d{yyyy-MM-dd HH:mm:ss,SSS} >>> %l%n[massage] %m%n}{FATAL=red, ERROR=red, WARN=yellow, INFO=cyan, DEBUG=cyan,TRACE=blue}"/>
        </Console>
        <RollingFile type="RollingFile" name="file" fileName="${LOG_HOME}/app.log" filePattern="${LOG_HOME}/%d{yyyy}-app-%i.zip" append="false"> 
<PatternLayout pattern="[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %l >>> %m%n" />
<Policies>
<TimeBasedTriggeringPolicy modulate="true" interval="1"/>
<SizeBasedTriggeringPolicy size="1024 MB"/> <!-- <SizeBasedTriggeringPolicy size="1k"/> --> </Policies> <DefaultRolloverStrategy max="3"> <!-- <Delete basePath="exp/" maxDepth="1"> --> <!-- <IfFileName glob="*.zip" /> --> <!-- <IfLastModified age="7d" /> --> <!-- </Delete> --> </DefaultRolloverStrategy> </RollingFile> <!--(error单独输出)--> <RollingFile name="error-file" fileName="${LOG_HOME}/error.log" filePattern="${LOG_HOME}/%d{yyyy}-error-%i.zip" append="false"> <PatternLayout pattern="[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %l >>> %m%n" /> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/><!--(只接收error单独输出)--> <Policies> <TimeBasedTriggeringPolicy modulate="true" interval="1"/> <SizeBasedTriggeringPolicy size="1024 MB"/> </Policies> <DefaultRolloverStrategy max="1"> </DefaultRolloverStrategy> </RollingFile> <RollingFile name="appinfo-file" fileName="${LOG_HOME}/appinfo/appinfo.log" filePattern="${LOG_HOME}/appinfo/$${date:yyyy-MM-dd}/appinfo-%d-%i.zip" append="false"> <PatternLayout pattern="%d [%t] %-5p > %m %n" /> <Policies> <!-- 每天换文件到日期目录 --> <TimeBasedTriggeringPolicy modulate="true" interval="1"/> <!-- 到文件大小后 移动到 filePattern指定目录 --> <SizeBasedTriggeringPolicy size="1024 MB"/> </Policies> <DefaultRolloverStrategy max="1"> <!-- <Delete basePath="exp/appinfo/" maxDepth="1"> --> <!-- <IfFileName glob="*.zip" /> --> <!-- <IfLastModified age="7d" /> --> <!-- </Delete> --> </DefaultRolloverStrategy> </RollingFile> </appenders> <loggers> <!--additivity="true" 若是additivity设为true,则子Logger不止会在自己的appender里输出,还会在root的logger的appender里输出 --> <logger name="error" level="info" additivity="true"> <appender-ref ref="console" /> <appender-ref ref="error-file" /> </logger> <logger name="appinfo" level="info" additivity="true"> <appender-ref ref="console" /> <appender-ref ref="appinfo-file" /> </logger> <logger name="org.springframework" level="info" additivity="false"> <appender-ref ref="console" /> <appender-ref ref="file" /> </logger> <logger name="org.springframework.jdbc.core" level="info" additivity="false"> <appender-ref ref="console" /> <appender-ref ref="file" /> </logger> <logger name="cn.com.testproject.core" level="debug" additivity="false"> <appender-ref ref="console" /> <appender-ref ref="file" /> </logger> <root level="debug"> <appender-ref ref="console" /> <appender-ref ref="file" /> <appender-ref ref="error-file" /><!--(只接收error单独输出)--> </root> </loggers> </configuration>

 同时注意log_home的传入,从外界不能直接使用${log_home},而是将外界的值,传递给property。

<properties>
<property name="LOG_HOME">${sys:LOG_HOME}</property>
</properties>

在使用的地方使用即可。${LOG_HOME}

 

log4j2下彩色设置:

<Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%highlight{[%p] %-d{yyyy-MM-dd HH:mm:ss,SSS} >>> %l%n[massage] %m%n}{FATAL=red, ERROR=red, WARN=yellow, INFO=cyan, DEBUG=cyan,TRACE=blue}"/> </Console>
<PatternLayout pattern="%highlight{[ %p ] [%-d{yyyy-MM-dd HH:mm:ss}] [ LOGID:%X{logid} ] [%l] %m%n}"/>

以上的形式%highlight{****}即可。

但是在log4j2.10后,在2.10版本以后,Log4j2默认关闭了Jansi(一个支持输出ANSI颜色的类库)。

IDEA: Run -》 Edit Configurations -》Environment,在VM options中添加
-Dlog4j.skipJansi=false
Eclipse :Run Configurations->Arguments-> VM arguments
-Dlog4j.skipJansi=false

参见:https://blog.youkuaiyun.com/zzc199055/article/details/86706695

 注意:

RollingFile 一定要加 type=“RollingFile”,因为name我们可能会随意起,而不是使用RollingFile,因此用type来声明。

 如果发现某些配置不起作用,可将configuration变为 trace来获取具体信息,平时设置为 status="OFF"

<configuration status="trace" 

删除无用文件可参考以下写法:

<DefaultRolloverStrategy max="5">
                <Delete basePath="${LOG_HOME}" maxDepth="1">
                    <IfFileName glob="appManager-*.log.zip">
                        <IfAny>
                            <IfAccumulatedFileCount exceeds="1"/>
                        </IfAny>
                    </IfFileName>

<!--                    <IfLastModified age="5d" />-->
                </Delete>

 

此处有篇文章讲的非常详细关于log4j2中的参数使用

http://www.bubuko.com/infodetail-2413996.html

log4j2的官方文档: http://logging.apache.org/log4j/2.x/manual/appenders.html#RollingFileAppender

 

转载于:https://www.cnblogs.com/DennyZhao/p/10374326.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值