SpringBoot入门建站全系列(七)日志组件的使用

SpringBoot入门建站全系列(七)日志组件的使用

前面六篇已经对SpringBoot的基础用做了介绍,日常项目使用已经足够,本篇介绍下SpringBoot日志使用的注意事项。

项目地址:
品茗IT-同步发布

品茗IT 提供在线支持:

一键快速构建Spring项目工具

一键快速构建SpringBoot项目工具

一键快速构建SpringCloud项目工具

一站式Springboot项目生成

Mysql一键生成Mybatis注解Mapper

如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以加入我们的java学习圈,点击即可加入,共同学习,节约学习时间,减少很多在学习中遇到的难题。

一、日志组件科普

Java可以用的日志组件有很多的,这里不得不科普一下。

  • log4j是Apache的一个开源项目,专门打日志的。

  • logback同样是由log4j的作者设计完成的,拥有更好的特性,用来取代log4j的一个日志框架,是slf4j的原生实现(即直接实现了slf4j的接口,而log4j并没有直接实现,所以就需要一个适配器slf4j-log4j12.jar),也是个专门打日志的。

  • slf4j是java的一个日志门面,实现了日志框架一些通用的api,log4j和logback是具体的日志框架。也就是个日志中介,中间商赚差价。

  • Commons-logging是apache最早提供的日志的门面接口。提供简单的日志实现以及日志解耦功能,也是个打日志的,就是有点弱。

现在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.

这段话困惑了我很久,网上的乱七八糟说明都只是翻译了一遍,鸟用都没,真想喷死他们这些搬运工。

这段话的意思其实是:

    1. SpringBoot自己用的是Commons Logging这个日志组件,但是允许使用其他日志实现。为什么用Commons Logging呢?可能是SpringBoot对Commons Logging这个jar包是必须依赖的,为了不额外引入日志组件,就用它了呗。
    1. 如果用了“Starters”,默认的日志组件就是Logback,这句话困惑了很久,后来跟踪日志实现,查看了依赖结构才发现,它说的这个“Starters”指的是"spring-boot-starter-logging",我们在引入spring-boot-starter-web的时候,就已经引入了spring-boot-starter-logging,看图:

在这里插入图片描述

三、快速配置日志方法(已经可用了)

什么都不用配,什么都不用管,只要几个配置就完事儿了,前提引入了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 SystemCustomization
Logbacklogback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2log4j2-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(为赋新词强说愁)

不知道有多少人愿意用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>
5.1 log4j2快速配置

同样可以使用配置文件里直接配置的方法使用,跟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
5.2 xml方式配置

SpringBoot官网写的日志组件读取的默认配置文件:

Logging SystemCustomization
Logbacklogback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2log4j2-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>

其他的实现就不讲了,非主流实现自己看官方文档吧。。

快速构建项目

Spring组件化构建

喜欢这篇文章么,喜欢就加入我们一起讨论SpringBoot技术吧!
品茗IT交流群

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值