使用Log4J来作为Spring Boot的日志系统

柔情痞子 提交于 2019-12-07 20:35:13

1. 修改build.gradle

排除掉对logback的依赖,添加对log4j的依赖

dependencies {
	compile('org.springframework.boot:spring-boot-starter-web') {
		exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' 
	}
	compile('org.slf4j:slf4j-api')
	compile('org.slf4j:slf4j-log4j12')
	compile('commons-logging:commons-logging')

}

2.设置定log4j的配置文件位置,例如:

log4j-dev.xml文件放到src/main/resources目录下,然后在application.properties文件里设置

logging.config=classpath:log4j-dev.xml

3. 在Spring Boot的启动类里用代码手动加载log4j,例如:

@SpringBootApplication
public class Application implements EnvironmentAware {

	private Environment env;

	@Value('${logging.config}')
	private String log4jName;

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.env = environment;
		String[] dProfiles = env.getDefaultProfiles();
		String[] aProfiles = env.getActiveProfiles();

		System.out.println("Spring DefaultProfiles:" + java.util.Arrays.asList(dProfiles));
		System.out.println("Spring ActiveProfiles:" + java.util.Arrays.asList(aProfiles));
		if (aProfiles.length == 0) {
			System.out.println("Please set 'spring.profiles.active'");
			System.exit(-1);
		}

		//加载Log4J配置文件
		DOMConfigurator.configure(org.springframework.util.ResourceUtils.getURL(log4jName));
		Logger log = LoggerFactory.getLogger(this.getClass());

		log.info("当前ActiveProfiles:"+env.getActiveProfiles().toString());
	}
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!