使用Log4J來作爲Spring Boot的日誌系統 頂 原

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());
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章