一,为什么要使用log4j2?
log4j2是log4j的升级版,
升级后更有优势:
性能更强/吞吐量大/支持异步
功能扩展/支持插件/支持自定义级别等
这些优势可以从它的官网了解
log4j2官方网站:
https://logging.apache.org/log4j/2.x/
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,本演示项目的相关信息
1,项目地址:
https://github.com/liuhongdi/tomcatlogs
2,项目原理:
生成两个日志:
bussiness日志:负责记录业务相关的日志
error日志:负责记录系统中的错误日志
3,项目结构:
三, log4j2的相关配置
1,日志级别的优先级:
ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF
说明:如果我们设置日志级别为:WARN,
则记录的级别包括:WARN / ERROR / FATAL / OFF。
2,logger的additivity属性:
如果设置为false,logger不会把日志流添加到root的日志
如果设置为true,则会添加到root的日志
说明:如果是异步日志时,建议设置为false
3,Appender的immediateFlush属性:
作用:立刻刷写到磁盘
如果设置为false,能明显示的提升性能
即使是同步日志也有帮助
4,includeLocation=“true”
说明:includeLocation用来获取类的路径,
值只有设置为true时才会生效
5,AsyncRoot/AsyncLogger都需要用到disruptor功能,
所以无论用哪个都需要引入disruptor功能包
四,配置文件说明:
1,pom.xml
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-starter-log4j2
com.lmax
disruptor
3.4.2
说明1:spring-boot-starter-web默认包含了日志功能包,
包含了logback/slf4j两个日志包,
所以我们需要用excusion排除对此两个包的依赖
说明2:log4j的异步日志使用了Disruptor的队列技术,
我们需要使用异步日志,所以这里需要引入Disruptor,
附:Disruptor在mvn上的地址:可以从这里查看版本
https://mvnrepository.com/artifact/com.lmax/disruptor
2,application.properties
#log4j2
logging.config=classpath:log4j2.xml
说明:指定log4j2配置文件的路径,放到resources目录下
3,log4j2.xml:
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n
说明:
ErrorFile放到asyncRoot下,用来记录系统的所有信息
BusinessFile则用来记录业务相关的日志(需要靠代码生成日志)
五,java代码说明
1,homecontroller.java
@RestController
@RequestMapping("/home")
public class HomeController {
@GetMapping("/list")
@ResponseBody
public String list() {
Logger logger1=LogManager.getLogger(this.getClass());
Logger logger2= LogManager.getLogger("BusinessFile");
logger1.info("hello,this is in errorlog");
logger2.info("hello,this is in businesslog");
return"this is list";
}
}
说明:
获取logger时,如果使用class,会保存到root下指定的日志
如果使用指定的日志AppenderRef名字,则会保存到名字对应的日志
六,测试写日志的效果:
1,访问url
http://127.0.0.1:8080/home/list
2,查看所写入的日志:
[liuhongdi@localhost tomcatlogs]$ tail -1bussiness.log2020-07-05 22:46:07.208 [http-nio-8080-exec-7] [:] INFO BusinessFile - hello,this is inbusinesslogge
[liuhongdi@localhost tomcatlogs]$tail -1error.log2020-07-05 22:46:07.208 [http-nio-8080-exec-7] [HomeController.java:20] INFO com.tomcatlogs.demo.controller.HomeController - hello,this is in errorlog
可以看到日志写入成功
七,查看spring boot的版本:
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
(( )\___ | '_ |'_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| |) ) ) )'|____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v2.3.1.RELEASE)