SpringBoot log4j2

1、pom.xml 引入依赖

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.olive</groupId>
  5. <artifactId>valid-log4j2</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>jar</packaging>
  8. <parent>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-parent</artifactId>
  11. <version>2.1.8.RELEASE</version>
  12. <relativePath />
  13. </parent>
  14. <name>valid-demo</name>
  15. <url>http://maven.apache.org</url>
  16. <properties>
  17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. <exclusions><!-- 去掉springboot默认配置 -->
  24. <exclusion>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-logging</artifactId>
  27. </exclusion>
  28. </exclusions>
  29. </dependency>
  30. <dependency> <!-- 引入log4j2依赖 -->
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-log4j2</artifactId>
  33. </dependency>
  34. </dependencies>
  35. </project>

因为 SpringBoot 默认使用 logback 记录日志。所以要排除 logback 日志框架spring-boot-starter-logging,在引入 log4j2日志框架 spring-boot-starter-log4j2。

2、Controller 控制器编写

Controller 基本框架

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import org.apache.logging.log4j.Level;
  4. import org.apache.logging.log4j.LogManager;
  5. import org.apache.logging.log4j.core.LoggerContext;
  6. import org.apache.logging.log4j.core.config.Configuration;
  7. import org.apache.logging.log4j.core.config.LoggerConfig;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.slf4j.impl.StaticLoggerBinder;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. @RestController
  14. public class LoggerController {
  15. private final static Logger logger = LoggerFactory.getLogger(LoggerController.class);
  16. // TODO
  17. }

打印各级别日志

  1. @RequestMapping("/logger/print")
  2. public Map loggerPrint(){
  3. Map result = new HashMap();
  4. result.put("code", 200);
  5. result.put("msg", "success");
  6. logger.debug("loggerPrint debug>>>>");
  7. logger.info("loggerPrint info>>>>");
  8. logger.warn("loggerPrint warn>>>>");
  9. logger.error("loggerPrint error>>>>");
  10. return result;
  11. }

打印所有日志对象

  1. @RequestMapping("/logger/printAllLogger")
  2. public Map printAllLogger(){
  3. Map result = new HashMap();
  4. result.put("code", 200);
  5. result.put("msg", "success");
  6. LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  7. Configuration config = ctx.getConfiguration();
  8. Map<String, LoggerConfig> loggerConfigs = config.getLoggers();
  9. System.out.println("printAllLogger begin>>>>>>>>");
  10. loggerConfigs.forEach((name, loggerConfig) -> {
  11. System.out.println("name = " + name);
  12. System.out.println("loggerConfig = " + loggerConfig);
  13. });
  14. System.out.println("printAllLogger end>>>>>>>>");
  15. return result;
  16. }

动态设置日志对象的日志级别

  1. @RequestMapping("/logger/level")
  2. public Map loggerLevelChange(String level){
  3. Map result = new HashMap();
  4. result.put("code", 200);
  5. result.put("msg", "success");
  6. String loggerFactoryClassStr = StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr();
  7. System.out.println("loggerFactoryClassStr>>>>" + loggerFactoryClassStr);
  8. LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  9. Configuration config = ctx.getConfiguration();
  10. LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
  11. switch (level) {
  12. case "debug":
  13. loggerConfig.setLevel(Level.DEBUG);
  14. break;
  15. case "info":
  16. loggerConfig.setLevel(Level.INFO);
  17. break;
  18. case "warn":
  19. loggerConfig.setLevel(Level.WARN);
  20. break;
  21. case "error":
  22. loggerConfig.setLevel(Level.ERROR);
  23. break;
  24. default:
  25. break;
  26. }
  27. ctx.updateLoggers();
  28. return result;
  29. }

3、log4j2-spring.xml 配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
  3. <!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
  4. <configuration monitorInterval="5">
  5. <!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
  6. <!--变量配置-->
  7. <Properties>
  8. <!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
  9. <!-- %logger{36} 表示 Logger 名字最长36个字符 -->
  10. <property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
  11. </Properties>
  12. <appenders>
  13. <console name="ConsoleOut" target="SYSTEM_OUT">
  14. <!--输出日志的格式-->
  15. <PatternLayout pattern="${LOG_PATTERN}"/>
  16. <!--控制台只输出level及其以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
  17. <!-- <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/> -->
  18. </console>
  19. </appenders>
  20. <loggers>
  21. <root level="debug">
  22. <appender-ref ref="ConsoleOut"/>
  23. </root>
  24. </loggers>
  25. </configuration>

这里只配置了打印到控制台的 ROOT logger。

4、编写引导类

  1. @SpringBootApplication
  2. public class Application
  3. {
  4. public static void main( String[] args )
  5. {
  6. SpringApplication.run(Application.class, args);
  7. }
  8. }

启动服务

打印各级别日志

2021-05-14-21-52-22-481535.png
因为 log4j2-spring.xml 配置的级别是 debug,所以可以在控制台看到如下打印

  1. 21:08:52.298 [http-nio-8080-exec-1] DEBUG com.olive.controller.LoggerController - loggerPrint debug>>>>
  2. 21:08:52.298 [http-nio-8080-exec-1] INFO com.olive.controller.LoggerController - loggerPrint info>>>>
  3. 21:08:52.298 [http-nio-8080-exec-1] WARN com.olive.controller.LoggerController - loggerPrint warn>>>>
  4. 21:08:52.298 [http-nio-8080-exec-1] ERROR com.olive.controller.LoggerController - loggerPrint error>>>>

打印所有日志对象

2021-05-14-21-52-24-788720.png
在控制台只看见打印了 ROOT logger 对象。

  1. printAllLogger begin>>>>>>>>
  2. name =
  3. loggerConfig = root
  4. printAllLogger end>>>>>>>>

动态修改日志的级别

2021-05-14-21-52-25-099810.png
再次调用 http://127.0.0.1:8080/logger/print 接口打印日志,在控制台看到不在打印 debug 级别日志

  1. 21:19:25.756 [http-nio-8080-exec-6] INFO com.olive.controller.LoggerController - loggerPrint info>>>>
  2. 21:19:25.756 [http-nio-8080-exec-6] WARN com.olive.controller.LoggerController - loggerPrint warn>>>>
  3. 21:19:25.756 [http-nio-8080-exec-6] ERROR com.olive.controller.LoggerController - loggerPrint error>>>>

修改 log4j2-spring.xml 配置

  1. <loggers>
  2. <root level="debug">
  3. <appender-ref ref="Console"/>
  4. </root>
  5. <logger name="org.springframework" level="info" additivity="true">
  6. </logger>
  7. <logger name="org.hibernate" level="warn" additivity="true">
  8. </logger>
  9. </loggers>

重启服务,再次调用 http://127.0.0.1:8080/logger/printAllLogger 接口打印日志对象

  1. printAllLogger begin>>>>>>>>
  2. name =
  3. loggerConfig = root
  4. name = org.springframework
  5. loggerConfig = org.springframework
  6. name = org.hibernate
  7. loggerConfig = org.hibernate
  8. printAllLogger end>>>>>>>>