SpringBoot 默认使用的是Logback
1. 在resource新建文件logback-spring.xml,配置日志相关信息
XML
<configuration>
<property name="app.name" value="order-service"/>
<property name="log.path" value="./logs/" />
<!-- 设置日志级别 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!-- 配置文件输出 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/${app.name}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/${app.name}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!--日志文件保留天数-->
<maxHistory>7</maxHistory>
<TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!--日志文件最大的大小-->
<maxFileSize>1MB</maxFileSize>
</TimeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!-- 设置根logger -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
<!-- 设置特定包的日志级别 -->
<logger name="com.beiyou" level="DEBUG" />
</configuration>
结果:
2. 直接在application.properties(yml也可)中配置(推荐)
XML
#日志配置
logging.level.root=error
logging.level.com.beiyou=debug
# Console Appender
logging.pattern.console=${spring.application.name} %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %clr(%-5level) %green(%logger{36}) --- %msg%n
# File Appender
logging.file.name=./logs/${spring.application.name}.log
logging.pattern.file=${spring.application.name} [%date] %level [%thread] %logger{36} [%file:%line] %msg%n
logging.file.max-size = 1MB
logging.file.max-history = 7
结果:
此处默认压缩,logback-spring.xml亦可配置。
4.优先级
如果application.properties与logback-spring.xml同时配置,以logback-spring.xml为准,也就是说logback-spring.xml的优先级比较高