
spring boot 使用log4j 打印时,需首先去除自带 Logger ,然后加入log4j 依赖
<dependencies> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <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> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency>
然后加载自定义 log4j 配置文件,比如我们把 log4j 文件放到 resources/config/log4j/log4j.xml 下,
在启动 spring 之前,加载 log4j 文件
/** * 初始化 log4j */ public static void loadLog4j() { DOMConfigurator configurator = new DOMConfigurator(); ClassLoader classLoader = Application.class.getClassLoader(); URL url = classLoader.getResource(GlobalConstant.FilePath.log4j_file); configurator.doConfigure(url, LogManager.getLoggerRepository()); } public static void main(String[] args) throws Exception { //加载 log4j文件 loadLog4j(); SpringApplication.run(Application.class, args); }