前面六篇已经对SpringBoot的基础用做了介绍,日常项目使用已经足够,本篇介绍下SpringBoot日志使用的注意事项。
Java可以用的日志组件有很多的,这里不得不科普一下。
现在SpringBoot一般都用slf4j + logback来打日志。比较挑的人非要把logback换成log4j。无所谓咯,反正不是我写代码,不过我还是会尝试下换成log4j,反正也不难。
SpringBoot官网有这么一段话:
Spring Boot uses Commons Logging for all internal logging but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2, and Logback. In each case, loggers are pre-configured to use console output with optional file output also available.
By default, if you use the “Starters”, Logback is used for logging. Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J, or SLF4J all work correctly.
这段话困惑了我很久,网上的乱七八糟说明都只是翻译了一遍,鸟用都没,真想喷死他们这些搬运工。
这段话的意思其实是:
什么都不用配,什么都不用管,只要几个配置就完事儿了,前提引入了spring-boot-starter-web。当然这句也是废话,不引入这个玩个屁的Springboot。
下面是我的完整的配置:
server.port=8080
#log
logging.file=logs/stdout.log
logging.file.max-size=20KB
logging.pattern.file=%date [%thread][IP:%X{ip}|USER:%X{user}][%-5level %logger{80}] %msg%n
logging.pattern.console=%date [%thread][IP:%X{ip}|USER:%X{user}][%-5level %logger{80}] %msg%n
logging.level.root=INFO
logging.level.com.cff=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR
我的log地址:
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cff.springbootwork.web.entity.WelEntity;
@RestController
@RequestMapping("/pub")
public class WebRest {
private Logger log = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/welCome", method = { RequestMethod.GET })
public WelEntity welCome(@RequestParam String reqType) {
log.info("测试请求数据为:{}",reqType);
String uuid = UUID.randomUUID().toString();
String welMsg = "welcome 程序猿";
if(reqType != null && "1000".equals(reqType)){
welMsg = "welcome 程序媛";
}
WelEntity welEntity = new WelEntity();
welEntity.setUuid(uuid);
welEntity.setWelMsg(welMsg);
return welEntity;
}
}
详细代码,可以访问品茗IT-博客《SpringBoot入门建站全系列(七)日志组件的使用》
打日志的时候用的是slf4j,具体实现是logback, 切记,尽量在在代码里直接不要使用具体实现的日志组件,不然万一哪天产品抽风了呢?slf4j可以以不变应万变,不改动代码。
在application.properties旁边加个logback.xml,这时读取的配置就是这个xml了。习惯xml配置的同学可以玩这个,但是个人认为在application.properties配置会更好看,足够大多数系统用了。
SpringBoot官网写的日志组件读取的默认配置文件:
Logging System | Customization |
---|---|
Logback | logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy |
Log4j2 | log4j2-spring.xml or log4j2.xml |
JDK (Java Util Logging) | logging.properties |
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%date [%thread][IP:%X{ip}|USER:%X{user}][%-5level %logger{80}] %msg%n</pattern>
</encoder>
</appender>
<substitutionProperty name="log.base" value="D:/test" />
<appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.base}/stdout.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/stdout.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 100MB -->
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%date [%thread][IP:%X{ip}|USER:%X{user}][%-5level %logger{80}] %msg%n</pattern>
</encoder>
</appender>
<appender name="ExceptionLoggerFileOut" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.base}/exception.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/exception.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 100MB -->
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%date [%thread][IP:%X{ip}|USER:%X{user}][%-5level %logger{80}] %msg%n</pattern>
</encoder>
</appender>
<logger name="com.shangde.common.sys.log.SysLogInterceptor" level="DEBUG" additivity="true" >
<appender-ref ref="ExceptionLoggerFileOut" />
</logger>
<logger name="com.cff" level="DEBUG" />
<logger name="com" level="INFO" />
<logger name="ch.qos.logback" level="INFO" />
<logger name="org.mybatis" level="INFO" />
<logger name="org" level="INFO" />
<logger name="springfox" level="INFO" />
<root>
<level value="DEBUG" />
<appender-ref ref="stdout" />
<appender-ref ref="rollingFile" />
</root>
</configuration>
不知道有多少人愿意用log4j,反正配置起来没有logback简单,我是不太喜欢咯。但是还是写出来,方便大家。
要使用log4j,首先要排除已经依赖的spring-boot-starter-logging,然后手动引入spring-boot-starter-log4j2。
依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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>
同样可以使用配置文件里直接配置的方法使用,跟logback使用一样。
server.port=8080
#log
logging.file=logs/stdout.log
logging.file.max-size=20KB
logging.pattern.file=%date [%thread][IP:%X{ip}|USER:%X{user}][%-5level %logger{80}] %msg%n
logging.pattern.console=%date [%thread][IP:%X{ip}|USER:%X{user}][%-5level %logger{80}] %msg%n
logging.level.root=INFO
logging.level.com.cff=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR
SpringBoot官网写的日志组件读取的默认配置文件:
Logging System | Customization |
---|---|
Logback | logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy |
Log4j2 | log4j2-spring.xml or log4j2.xml |
JDK (Java Util Logging) | logging.properties |
如果不想用配置文件,还是习惯xml,可以这样配置:
log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="OFF" monitorInterval="1800">
<properties>
<property name="LOG_HOME">D:/test</property>
<property name="FILE_NAME">stdout</property>
</properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<RollingFile name="running-log" fileName="${LOG_HOME}/${FILE_NAME}.log"
filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd}-%i.log.gz"
immediateFlush="true">
<PatternLayout
pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.cff" level="debug" additivity="true">
<AppenderRef ref="running-log" />
<AppenderRef ref="Console" />
</Logger>
<Root level="info">
<!-- 这里是输入到文件,很重要 -->
<AppenderRef ref="running-log" />
<!-- 这里是输入到控制台 -->
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
其他的实现就不讲了,非主流实现自己看官方文档吧。。
喜欢这篇文章么,喜欢就加入我们一起讨论SpringBoot技术吧!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。