项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用myEclipse新建一个SpringBoot项目即可。现在来给项目添加一个log4j2支持,添加方式非常简单,仅需两步即可,具体内容如下:

1. pom.xml将原有的 logback 移除

<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>

2. pom.xml添加 log4j2包

<!-- 引入log4j2包 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

3.添加 log4j2.xml 配置文件到resources目录下(经测试放置在子目录下也是可以的,无需指定文件位置)

log4j2.xml的详细配置传送门==>《log4j2.xml完美配置》

4.重新发布启动项目即可

可以看到启动多出了很多日志信息,这是添加log4j2之前所没有的

5.实现方式

5.1 log4j2实现
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("test/v01")
public class TestV01Controller {
	private final Logger log = LogManager.getLogger();
	@RequestMapping("test")
	public String test(){
		for (int i = 0; i < 10; i++) {
			log.debug("第{}条log4j2的debug日志", i+1);
		}
		for (int i = 0; i < 20; i++) {
			log.info("第{}条log4j2的info日志", i+1);
		}
		for (int i = 0; i < 30; i++) {
			log.error("第{}条log4j2的error日志", i+1);
		}
		return "ok";
	}
}
5.2 slf4j实现(建议采用此实现方式,以增强日志兼容性,如若将来想要更换日志系统,此方式不用修改代码)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("test/v02")
public class TestV02Controller {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@RequestMapping("test")
	public String test(){
		for (int i = 0; i < 10; i++) {
			logger.debug("第{}条slf4j的debug日志", i+1);
		}
		for (int i = 0; i < 20; i++) {
			logger.info("第{}条slf4j的info日志", i+1);
		}
		for (int i = 0; i < 30; i++) {
			logger.error("第{}条slf4j的error日志", i+1);
		}
		return "ok";
	}
}