参考资料

pom.xml

  1. <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j2 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-log4j2</artifactId>
  5. <version>2.1.5.RELEASE</version>
  6. </dependency>

安装

首先需要屏蔽 Spring Boot 自带的 Log 工具,修改 pom.xml

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-logging</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>
  11. <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j2 -->
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-log4j2</artifactId>
  15. </dependency>

配置

新建 resources/log4j2.xml 文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <Configuration status="WARN">
  3. <Appenders>
  4. <Console name="Console" target="SYSTEM_OUT">
  5. <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
  6. </Console>
  7. </Appenders>
  8. <Loggers>
  9. <Root level="error">
  10. <AppenderRef ref="Console"/>
  11. </Root>
  12. </Loggers>
  13. </Configuration>

application.properties 中配置:

  1. logging.config=classpath:log4j2.xml

这里有一个官方的配置参考:https://logging.apache.org/log4j/2.x/manual/configuration.html#XML

使用

  1. package com.example.demo;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. /**
  5. * 演示如何使用 Logger
  6. *
  7. * @author Where
  8. */
  9. public class Demo {
  10. private static final Logger logger = LoggerFactory.getLogger(Demo.class);
  11. public void index() {
  12. logger.info("index");
  13. }
  14. }