Spring Boot使用Log4j2的实例代码
程序员文章站
2024-02-13 10:36:52
前言
spring boot 默认使用logback,来打印日志,这里还想说的slfj(simple logging facade for java),它们之间的关系,一...
前言
spring boot 默认使用logback,来打印日志,这里还想说的slfj(simple logging facade for java),它们之间的关系,一张图,说明一切:
maven 配置
<!--use log4j2 property--> <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> <!--flume log4j appender--> <dependency> <groupid>org.apache.logging.log4j</groupid> <artifactid>log4j-flume-ng</artifactid> <version>2.6</version> </dependency>
log4j2.xml 配置
log4j2 提供非常丰富的appender,比如cassandraappender,asyncappender,我们这里配置了简单的flume appnder,failover appender.
<?xml version="1.0" encoding="utf-8"?> <configuration monitorinterval="60"> <properties> <property name="source">api-web</property> <property name="log-pattern">%d{yyyy-mm-dd hh:mm:ss.sss} [%x{userid}] [%t] [%-5level] %c{1.}@%m%l - %m%n</property> <!--get product dynamic property--> </properties> <appenders> <rollingfile name="rollingfile" filename="logs/app.log" filepattern="logs/$${date:yyyy-mm}/app-%d{mm-dd-yyyy}-%i.log.gz"> <patternlayout> <pattern>${log-pattern}</pattern> </patternlayout> <policies> <timebasedtriggeringpolicy /> <sizebasedtriggeringpolicy size="250 mb"/> </policies> </rollingfile> <flume name="eventlogger" compress="false" type="avro" ignoreexceptions="false"> <agent host="192.168.31.115" port="4444"/> <agent host="127.0.0.1" port="4444"/> <patternlayout> <pattern> <pattern>${log-pattern}</pattern> </pattern> </patternlayout> </flume> <console name="console-appender" target="system_out" ignoreexceptions="false"> <patternlayout> <pattern>${log-pattern}</pattern> </patternlayout> </console> <!-- 主要apeender失败的时候使用备用appender--> <failover name="failover" primary="eventlogger"> <failovers> <appenderref ref="rollingfile"/> </failovers> </failover> </appenders> <loggers> <!--在需要同时打印文件和发送至flume的时候使用--> <!--<logger name="" level="info" additivity="false">--> <!--<appenderref ref="rollingfile"/>--> <!--</logger>--> <root level="info"> <appenderref ref="console-appender"/> <appenderref ref="failover"/> </root> </loggers> </configuration>
总结
如果遇到识别不了log4j2.properties/xml,可以在application.properties,中指定 logging.config=classpath:log4j2.properties/xml
参考
http://logging.apache.org/log4j/2.x/manual/appenders.html#rollingfileappender
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持
上一篇: java时间相关处理小结
推荐阅读