Log4j2介绍
Log4j -> Apache的一个开源项目,可以控制日志信息输送的目的地是控制台、文件、GUI组件等,可以控制每一条日志的输出格式,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
Log4j2 -> 相当于Log4j的一个升级版,但是已经被完全重写了。并且Log4j2性能优异,配置简单。
SpringBoot整合步骤
pom文件依赖
springboot默认是用logback的日志框架的,所以需要排除logback,不然会出现jar依赖冲突的报错。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions> <!-- 去掉spring boot默认log模块 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <!-- 引入log4j2依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency> <!-- 加上这个才能识别到log4j2.yml文件 -->
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<dependency> <!-- 方便log4j2代码调用 -->
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
配置文件
我们这里使用log4j2.yml格式来代替传统的log4j2.xml格式,yml格式提高了可阅读性。
Configuration:
status: warn # log4j2自己的日志级别
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
Properties: # 定义全局变量
Property:
- name: log.level.console # 输出到控制台的日志级别
value: info
- name: log.path
value: /var/log # 日志路径
- name: project.name
value: demo # 修改为你自己的项目名称
Appenders:
Console: # 输出到控制台
name: CONSOLE
target: SYSTEM_OUT
ThresholdFilter:
level: ${sys:log.level.console} # “sys:”表示:如果VM参数中没指定这个变量值,则使用本文件中定义的缺省全局变量值
onMatch: ACCEPT
onMismatch: DENY
PatternLayout:
pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
RollingFile: # 输出到文件,超过128MB归档
- name: ROLLING_FILE
ignoreExceptions: false
fileName: ${log.path}/${project.name}.log
filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
PatternLayout:
pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
Policies:
SizeBasedTriggeringPolicy:
size: "128 MB"
DefaultRolloverStrategy:
max: 1000
Loggers:
Root:
level: info
AppenderRef:
- ref: CONSOLE
- ref: ROLLING_FILE
示例代码
@Slf4j
@RestController
@RequestMapping(value = "/")
public class DemoController {
@GetMapping(value = "/")
public String get(){
System.out.println("get function for root path");
log.info("get function for root path");
return "hello root world";
}
@GetMapping(value = "/index")
public String index(){
System.out.println("get function for index path");
log.info("get function for index path");
return "hello index world";
}
}
最终效果
启用项目
[root@xxxx]# java -jar demo.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.1.RELEASE)
2020-07-14 15:27:54.420 INFO 2646 --- [ main] c.e.d.DemoApplication : Starting DemoApplication v0.0.1 with PID 2646 (/tmp/demo.jar started by root in /tmp)
2020-07-14 15:27:54.430 INFO 2646 --- [ main] c.e.d.DemoApplication : No active profile set, falling back to default profiles: default
2020-07-14 15:27:55.718 INFO 2646 --- [ main] o.s.b.w.e.t.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-07-14 15:27:55.744 INFO 2646 --- [ main] o.a.c.c.StandardService : Starting service [Tomcat]
2020-07-14 15:27:55.744 INFO 2646 --- [ main] o.a.c.c.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.36]
2020-07-14 15:27:55.819 INFO 2646 --- [ main] o.a.c.c.C.[.[.[/] : Initializing Spring embedded WebApplicationContext
2020-07-14 15:27:55.819 INFO 2646 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1338 ms
2020-07-14 15:27:56.020 INFO 2646 --- [ main] o.s.s.c.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-07-14 15:27:56.346 INFO 2646 --- [ main] o.s.b.w.e.t.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-07-14 15:27:56.359 INFO 2646 --- [ main] c.e.d.DemoApplication : Started DemoApplication in 2.724 seconds (JVM running for 4.093)
2020-07-14 15:28:21.300 INFO 2646 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-07-14 15:28:21.301 INFO 2646 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-07-14 15:28:21.308 INFO 2646 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : Completed initialization in 7 ms
get function for index path
2020-07-14 15:28:21.343 INFO 2646 --- [nio-8080-exec-1] c.e.d.c.demo : get function for index path
get function for root path
2020-07-14 15:28:25.050 INFO 2646 --- [nio-8080-exec-2] c.e.d.c.demo : get function for root path
浏览器中访问
查看日志文件内容
[root@xxx]# cat /var/log/demo.log
2020-07-14 15:32:39,909:INFO main (StartupInfoLogger.java:55) - Starting DemoApplication v0.0.1 with PID 2815 (/tmp/demo.jar started by root in /tmp)
2020-07-14 15:32:39,921:INFO main (SpringApplication.java:651) - No active profile set, falling back to default profiles: default
2020-07-14 15:32:41,132:INFO main (TomcatWebServer.java:108) - Tomcat initialized with port(s): 8080 (http)
2020-07-14 15:32:41,156:INFO main (DirectJDKLog.java:173) - Initializing ProtocolHandler ["http-nio-8080"]
2020-07-14 15:32:41,156:INFO main (DirectJDKLog.java:173) - Starting service [Tomcat]
2020-07-14 15:32:41,157:INFO main (DirectJDKLog.java:173) - Starting Servlet engine: [Apache Tomcat/9.0.36]
2020-07-14 15:32:41,236:INFO main (DirectJDKLog.java:173) - Initializing Spring embedded WebApplicationContext
2020-07-14 15:32:41,237:INFO main (ServletWebServerApplicationContext.java:285) - Root WebApplicationContext: initialization completed in 1260 ms
2020-07-14 15:32:41,505:INFO main (ExecutorConfigurationSupport.java:181) - Initializing ExecutorService 'applicationTaskExecutor'
2020-07-14 15:32:41,670:INFO main (DirectJDKLog.java:173) - Starting ProtocolHandler ["http-nio-8080"]
2020-07-14 15:32:41,697:INFO main (TomcatWebServer.java:220) - Tomcat started on port(s): 8080 (http) with context path ''
2020-07-14 15:32:41,711:INFO main (StartupInfoLogger.java:61) - Started DemoApplication in 2.356 seconds (JVM running for 3.982)
2020-07-14 15:32:47,976:INFO http-nio-8080-exec-1 (DirectJDKLog.java:173) - Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-07-14 15:32:47,976:INFO http-nio-8080-exec-1 (FrameworkServlet.java:525) - Initializing Servlet 'dispatcherServlet'
2020-07-14 15:32:47,985:INFO http-nio-8080-exec-1 (FrameworkServlet.java:547) - Completed initialization in 9 ms
2020-07-14 15:32:48,015:INFO http-nio-8080-exec-1 (demo.java:15) - get function for root path
2020-07-14 15:32:50,493:INFO http-nio-8080-exec-3 (demo.java:22) - get function for index path