Log4j2日志框架在SpringBoot中的应用
1. SpringBoot自带的日志框架 SpringBoot默认的日志框架为LogBack
GitHub地址:
Logback:https://github.com/qos-ch/logback
感觉Logback作者有段时间没更新了
在启动项依赖中点进去可以依次看到包含依赖 <artifactId > spring-boot-starter-web</artifactId > ↓ <artifactId > spring-boot-starter</artifactId > ↓ <artifactId > spring-boot-starter-logging</artifactId > ↓ <dependency > <groupId > ch.qos.logback</groupId > <artifactId > logback-classic</artifactId > <scope > compile</scope > </dependency > <dependency > <groupId > org.apache.logging.log4j</groupId > <artifactId > log4j-to-slf4j</artifactId > <scope > compile</scope > </dependency > <dependency > <groupId > org.slf4j</groupId > <artifactId > jul-to-slf4j</artifactId > <scope > compile</scope > </dependency >
因为是默认配置好的,实际需要配置的并不多。
如果需要输出日志到文件,只需要在application.properties配置文件设置:logging.file或logging.path,如下:
logging.level.root =info logging.file =D:\\log\\my.log
值得一提的是
Spring Boot官方建议使用“-spring”的命名规则对配置文件进行命名,如:logback-spring.xml而不是logback.xml。log4j2也是如此
也可以自定义日志名称,需要在application.properties配置即可,代如下:
logging.config=classpath:logging-config.xml
贴一个Logback的配置文件,其实log4j2的配置文件也是类似的。
<?xml version="1.0" encoding="UTF-8"?> <configuration > <springProperty scope ="context" name ="LOG_HOME" source ="logging.path" defaultValue ="/data/logs/spring-boot-logback" /> <springProperty scope ="context" name ="LOG_ROOT_LEVEL" source ="logging.level.root" defaultValue ="DEBUG" /> <springProperty scope ="context" name ="STDOUT" source ="log.stdout" defaultValue ="STDOUT" /> <property name ="LOG_PREFIX" value ="spring-boot-logback" /> <property name ="LOG_CHARSET" value ="UTF-8" /> <property name ="LOG_DIR" value ="${LOG_HOME}/%d{yyyyMMdd}" /> <property name ="LOG_MSG" value ="- | [%X{requestUUID}] | [%d{yyyyMMdd HH:mm:ss.SSS}] | [%level] | [${HOSTNAME}] | [%thread] | [%logger{36}] | --> %msg|%n " /> <property name ="MAX_FILE_SIZE" value ="50MB" /> <property name ="MAX_HISTORY" value ="10" /> <appender name ="STDOUT" class ="ch.qos.logback.core.ConsoleAppender" > <layout class ="ch.qos.logback.classic.PatternLayout" > <pattern > ${LOG_MSG}</pattern > </layout > </appender > <appender name ="0" class ="ch.qos.logback.core.rolling.RollingFileAppender" > </appender > <appender name ="FILE_ALL" class ="ch.qos.logback.core.rolling.RollingFileAppender" > <File > ${LOG_HOME}/all_${LOG_PREFIX}.log</File > <rollingPolicy class ="ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <FileNamePattern > ${LOG_DIR}/all_${LOG_PREFIX}%i.log</FileNamePattern > <MaxHistory > ${MAX_HISTORY}</MaxHistory > <timeBasedFileNamingAndTriggeringPolicy class ="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP" > <maxFileSize > ${MAX_FILE_SIZE}</maxFileSize > </timeBasedFileNamingAndTriggeringPolicy > </rollingPolicy > <layout class ="ch.qos.logback.classic.PatternLayout" > <pattern > ${LOG_MSG}</pattern > </layout > </appender > <appender name ="FILE_ERROR" class ="ch.qos.logback.core.rolling.RollingFileAppender" > <filter class ="ch.qos.logback.classic.filter.LevelFilter" > <level > ERROR</level > <OnMismatch > DENY</OnMismatch > <OnMatch > ACCEPT</OnMatch > </filter > <File > ${LOG_HOME}/err_${LOG_PREFIX}.log</File > <rollingPolicy class ="ch.qos.logback.core.rolling.TimeBasedRollingPolicy" > <FileNamePattern > ${LOG_DIR}/err_${LOG_PREFIX}%i.log</FileNamePattern > <MaxHistory > ${MAX_HISTORY}</MaxHistory > <timeBasedFileNamingAndTriggeringPolicy class ="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP" > <maxFileSize > ${MAX_FILE_SIZE}</maxFileSize > </timeBasedFileNamingAndTriggeringPolicy > </rollingPolicy > <layout class ="ch.qos.logback.classic.PatternLayout" > <Pattern > ${LOG_MSG}</Pattern > </layout > </appender > <logger name ="org.springframework" level ="ERROR" /> <logger name ="org.apache.commons" level ="ERROR" /> <logger name ="org.apache.zookeeper" level ="ERROR" /> <logger name ="com.alibaba.dubbo.monitor" level ="ERROR" /> <logger name ="com.alibaba.dubbo.remoting" level ="ERROR" /> <root level ="${LOG_ROOT_LEVEL}" > <appender-ref ref ="${STDOUT}" /> <appender-ref ref ="FILE_ALL" /> <appender-ref ref ="FILE_ERROR" /> </root > </configuration >
2. Log4j2日志框架 Log4j2是Log4j的升级,它比其前身Log4j 1.x(已停更)提供了重大改进,并提供了Logback中可用的许多改进,同时修复了Logback架构中的一些固有问题。比如:插件式结构、配置文件优化、异步日志等。
GitHub地址
log4j2:https://github.com/apache/logging-log4j2
可以看到的是更新还是很活跃的。
Spring Boot添加Log4j2依赖,需要排除Logback依赖,配置pom.xml代码如下:
<dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > <exclusions > <exclusion > <artifactId > org.springframework.boot</artifactId > <groupId > spring-boot-starter-logging</groupId > </exclusion > <exclusion > <groupId > org.slf4j</groupId > <artifactId > slf4j-log4j12</artifactId > </exclusion > </exclusions > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-log4j2</artifactId > </dependency >
在配置好后启动我这边会警告类似信息
SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/E:/mavenJarOnline/ch/qos/logback/logback-classic/1.1.9/logback-classic-1.1.9.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/E:/mavenJarOnline/org/slf4j/slf4j-log4j12/1.7.22/slf4j-log4j12-1.7.22.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http: SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
警告告知logging有多个绑定,logback、log4j2两种实现,明明已经排除了logback的依赖…
将spring-boot-starter-logging的包在spring-boot-starter中直接排除掉可以解决
<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-spring.xml
文件的配置
log4j2配置详解
<?xml version="1.0" encoding="UTF-8"?> <configuration monitorInterval ="5" > <Properties > <property name ="LOG_PATTERN" value ="%date{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger [%L] : %msg%n" /> <property name ="LOG_PATTERN_HIGHLIGHT" value ="%date{yyyy-MM-dd HH:mm:ss:SSS} %highlight{%5level} [%thread] %style{%logger}{bright,cyan} [%style{%L}{bright,blue}] : %msg%n" /> <property name ="FILE_PATH" value ="D://log4j2Logs" /> <property name ="FILE_NAME" value ="exception_demo" /> </Properties > <appenders > <console name ="Console" target ="SYSTEM_OUT" > <PatternLayout pattern ="${LOG_PATTERN_HIGHLIGHT}" /> <ThresholdFilter level ="info" onMatch ="ACCEPT" onMismatch ="DENY" /> </console > <File name ="Filelog" fileName ="${FILE_PATH}/test.log" append ="false" > <PatternLayout pattern ="${LOG_PATTERN}" /> </File > <RollingFile name ="RollingFileInfo" fileName ="${FILE_PATH}/info.log" filePattern ="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz" > <ThresholdFilter level ="info" onMatch ="ACCEPT" onMismatch ="DENY" /> <PatternLayout pattern ="${LOG_PATTERN}" /> <Policies > <TimeBasedTriggeringPolicy interval ="1" /> <SizeBasedTriggeringPolicy size ="10MB" /> </Policies > <DefaultRolloverStrategy max ="15" /> </RollingFile > <RollingFile name ="RollingFileWarn" fileName ="${FILE_PATH}/warn.log" filePattern ="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz" > <ThresholdFilter level ="warn" onMatch ="ACCEPT" onMismatch ="DENY" /> <PatternLayout pattern ="${LOG_PATTERN}" /> <Policies > <TimeBasedTriggeringPolicy interval ="1" /> <SizeBasedTriggeringPolicy size ="10MB" /> </Policies > <DefaultRolloverStrategy max ="15" /> </RollingFile > <RollingFile name ="RollingFileError" fileName ="${FILE_PATH}/error.log" filePattern ="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz" > <ThresholdFilter level ="error" onMatch ="ACCEPT" onMismatch ="DENY" /> <PatternLayout pattern ="${LOG_PATTERN}" /> <Policies > <TimeBasedTriggeringPolicy interval ="1" /> <SizeBasedTriggeringPolicy size ="10MB" /> </Policies > <DefaultRolloverStrategy max ="15" /> </RollingFile > </appenders > <loggers > <logger name ="org.mybatis" level ="info" additivity ="false" > <AppenderRef ref ="Console" /> </logger > <Logger name ="org.springframework" level ="info" additivity ="false" > <AppenderRef ref ="Console" /> </Logger > <root level ="info" > <appender-ref ref ="Console" /> <appender-ref ref ="Filelog" /> <appender-ref ref ="RollingFileInfo" /> <appender-ref ref ="RollingFileWarn" /> <appender-ref ref ="RollingFileError" /> </root > </loggers > </configuration >
3. Logger的使用 最简单的在类中使用就是
private static final Logger logger = LoggerFactory.getLogger(XXX.class ) ;logger.debug("debug信息" ); logger.info("info信息" ); logger.error("error信息" );
在项目运行后控制台输出如下
可以在配置的文件夹下面看到生成的日志文本
补充
IDEA更新后控制台彩色输出会失效,需要在右上角 -> Edit Configurations -> VM options中添加
-Dlog4j.skipJansi=false